Shona
Shona

Reputation: 261

Part I - Java Split String function

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

    }

}
}

Upvotes: 0

Views: 120

Answers (5)

Shona
Shona

Reputation: 261

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.

Upvotes: 1

James Allison
James Allison

Reputation: 135

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.

Upvotes: 1

gulshanm01
gulshanm01

Reputation: 195

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

Upvotes: 1

Mike Samuel
Mike Samuel

Reputation: 120526

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;
}

Upvotes: 3

christopher
christopher

Reputation: 27356

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];

Upvotes: 1

Related Questions