Thread: Substring Help

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2012
    Posts
    29
    Rep 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 = ""; 		 		
    System.out.println("Please enter a#,b#,c#: "); 	
    	
    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. #2
  3. Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Aug 2010
    Location
    Eastern Florida
    Posts
    3,696
    Rep 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.

IMN logo majestic logo threadwatch logo seochat tools logo