0

I am still new at java. I have this basic split string function as below. I need to capture the substrings post split. My question is how to move individually split parts into separate variables instead of printing them? Do I need another array to move them separately? Is there another simpler way to achieve this? In part I, for simplicity, I am assuming the delimiters to be spaces. Appreciate your help!

public class SplitString {

public static void main(String[] args) {

    String phrase = "First Second Third";
    String delims = "[ ]+";
    String[] tokens = phrase.split(delims);
    String first;
    String middle;
    String last;

    for (int i = 0; i < tokens.length; i++)
    {

        System.out.println(tokens[i]);
                //I need to move first part to first and second part to second and so on

    }

}
}
1
  • 1
    String thirdPart = tokens[2]? Commented Apr 4, 2014 at 13:24

5 Answers 5

3

array[index] accesses the indexth element of array, so

first = tokens[0];  // Array indices start at zero, not 1.
second = tokens[1];
third = tokens[2];

You should really check the length first, and if the string you're splitting is user input, tell the user what went wrong.

if (tokens.length != 3) {
  System.err.println(
      "I expected a phrase with 3 words separated by spaces,"
      + " not `" + phrase + "`");
  return;
}
Sign up to request clarification or add additional context in comments.

Comments

1

If the number of Strings that you will end up with after the split has taken place is known, then you can simply assign the variables like so.

 String first = tokens[0];
 String middle = tokens[1];
 String last = tokens[2];

If the number of tokens is not known, then there is no way (within my knowledge) to assign each one to a individual variable.

Comments

1

If you're assuming that your String is three words, then it's quite simple.

String first = tokens[0];
String middle = tokens[1];
String last = tokens[2];

Comments

1
if(tokens.length>3)
{
String first=tokens[0];
String middle=tokens[1];
String last=tokens[2];
}

Comments

1

Thanks everyone...all of you have answered me in some way or the other. Initially I was assuming only 3 entries in the input but turns out it could vary :) for now i'll stick with the simple straight assignments to 3 variables until I figure out another way! Thanks.

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.