简体   繁体   中英

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

    }

}
}

array[index] accesses the index th 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;
}

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];
if(tokens.length>3)
{
String first=tokens[0];
String middle=tokens[1];
String last=tokens[2];
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM