Java convert string to string array by spaces

12,921

Solution 1

You can simply split() your string on whitespace.

String[] words = name.split(" ");

Solution 2

You can use split() and create an array.

String name = "John Mark Lester Andrew Todd";
String[] names=name.split(" ");

Solution 3

What ever criteria or letter on the basis of which a string is to be split,that need to be provided under

  string.split(" ");

so,u can try using these updated code:::

 String name = "John Mark Lester Andrew Todd";
 String[] letters = name.split(" ");
 System.out.println("letters = " + Arrays.toString(letters));

and the ouput will be::

  letters = [John, Mark, Lester, Andrew, Todd]

And for better understanding for splitting the strings in java,you can go to this link. http://www.tutorialspoint.com/java/java_string_split.htm

Solution 4

The most flexible is to split on all whitespace:

String names = "John  \t\t  Mark  Lester \n  Andrew Todd \r";

System.out.println(Arrays.toString(names.split("\\s+")));

Outputs:

[John, Mark, Lester, Andrew, Todd]

\\s+ is regex for "any length of any whitespace characters". Similarly if you only care about spaces:

String names = "John  Mark  Lester   Andrew Todd  ";

System.out.println(Arrays.toString(names.split(" +")));

(Outputs same as above.)

Of course both of those will split single spaces too.

Solution 5

You can use :

String values=Arrays.toString(name.split(" "));

or

String values[] = name.split("\\s")
Share:
12,921
Dunkey
Author by

Dunkey

I love programming

Updated on June 15, 2022

Comments

  • Dunkey
    Dunkey almost 2 years

    I would like to convert string to string array.. I have done something like this:

    String name = "name";
    String[] letters = name.split("(?<=.)");
    System.out.println("letters = " + Arrays.toString(letters));
    

    But now I want something like this:

    String name = "John Mark Lester Andrew Todd";
    

    To print array like this:

    [John, Mark, Lest, Andrew, Todd]
    

    So I want to look for spaces in my string and then put them into a string array. Do you have ideas to do this? Help is much appreciated. Thanks.