tags:

views:

45

answers:

5

Hello, I need help splitting this string, but i can't seem to come with the right way of doing it. Suppose I have two numbers on a line

12 101

I would like to take the first and assign it to variable, and then take the second and assign it to a variable, this may sounds easy, but for me i can't come up with the right way to do it?

A: 
String[] result = myString.split(" ");

should work. Then you can assign the values to a variable from the array if you want. Though you should note that if there are two spaces, it will create an array with length of three, the middle element being an empty string.

Carlos
A: 
String s = "12 101";
String[] splitted = s.split("\s"); // \s = any whitespace character except newline
Femaref
A: 
String text = "12 101";
String[] splitted = text.split("\\s+");
System.out.println(splitted[0]);
System.out.println(splitted[1]);

Will print:

12
101

Using \s+ splits the string at every whitespace in your text. Multiple whitespaces are ignores.

Only doing split(" "); will result in empty fields (e.g. "102 12 4" => [102, , 12, 4]).

halfdan
it should be splitted[0] and splitted[1] instead of text[0] and text[1].
dogbane
You should put that last example in a code block so people can see the two spaces between `102` and `12`.
Alan Moore
A: 
String[] myStringArray = myString.split(" "); 

will split the string into an array myStringArray

JackN
+3  A: 

Split the string on space which will give you an array of strings that can be stored in two variables. If necessary, you can convert them to ints as shown below:

String text = "12 101";
String[] split= text.split("\\s+");
String first = split[0];
String second = split[1];

//if you want them as ints
int firstNum = Integer.parseInt(first);
int secondNum = Integer.parseInt(second);
dogbane