Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
September 19th, 2012, 09:54 PM
 cyimking
Registered User

Join Date: Sep 2012
Posts: 29
Time spent in forums: 11 h 19 m 56 sec
Reputation Power: 0
Substring Help

Ok, so i know this might be easy, but i do i used substring to split up a string in 4 different sections.

Example..

A user would make an input of :

A#,B#,C#,D# (# being a number).

And i want the substring to break it up so i can do convert the number to a double and then on...

So if the user input A3,B21,C20,D0...
The variables for a,b,c,d will be: a = 3, b = 21 , c = 20, d = 0.

Therefore i would have to use the method indexOf(",") and lastIndexOf(","). The code i have so far works when just use A#,B#,C#.. but when i go to add the D#, then i get confused..

Code:
```Scanner scan = new Scanner(System.in);

String t = "";

t = scan.nextLine();
int x = t.indexOf(",");
int y = t.lastIndexOf(",");

String a = t.substring(1 , x );		       //First part
String b = t.substring(x + 2 , y);         //Middle part
String c = t.substring(y + 2,  t.length()); //Last part

int aa = Integer.parseInt(a);
int bb = Integer.parseInt(b);
int cc = Integer.parseInt(c);

aa = aa * 5;
bb = bb * 5;
cc = cc * 5;

System.out.println(a + "\n"  + b + "\n" + c + "\n");
System.out.println("\n" + aa + "\n"  + bb + "\n" + cc );
```

#2
September 20th, 2012, 08:03 AM
 NormR
Contributing User

Join Date: Aug 2010
Location: SW Missouri
Posts: 3,610
Time spent in forums: 2 Weeks 3 Days 6 h 20 m 2 sec
Reputation Power: 347
Look at using the indexOf() method to find the location of the next "," past the last ","
Instead of starting at the beginning, start looking just past the last "," that was found.
See the API doc for the correct syntax.

 Viewing: Dev Shed Forums > Programming Languages > Java Help > Substring Help