0

String s = name1, name2, name3, name4

How would I extract name2, name3, and name4 from the String.

I know I have to use s.split(",") , but I am not sure how to code a loop that would ignore name1

2
  • you don't need a loop for this Commented Apr 12, 2014 at 23:13
  • did I answered your question? Commented Apr 12, 2014 at 23:18

3 Answers 3

2

@user3437460 has the correct answer but if you were specifically looking to use a loop you just need to start at index 1 to ignore the first token.

String[] tokens = input.split(",");

for (int i = 1; i < tokens.length; i++) {
   // do something with tokens[i]
}
Sign up to request clarification or add additional context in comments.

Comments

2

You don't really have to explicitly ignore it. If you tokenized the string, you can just ignore the first token by not using it.

Let me give you an example.

    String[]str= s.split(",");
    String name1 = str[0]; //Just ignore this
    String name2 = str[1];
    String name3 = str[2];
    String name4 = str[3];

Comments

0

After splitting, check the length of array and if contains more than 1 element, then read element at index 1 for name2.

Example":

String s = "name1, name2, name3, name4";

String [] names = s.split( "," );

String name2 = null;
if( names.length() > 1 ) {
  name2 = names[ 1 ];
}

System.out.println( name2 );

And to read further you can use other indexes on other names.

String name3 = names[ 2 ];
String name4 = names[ 3 ];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.