438

I need to split my String by spaces. For this I tried:

str = "Hello I'm your String";
String[] splited = str.split(" ");

But it doesn't seem to work.

rghome
  • 8,529
  • 8
  • 43
  • 62
safari
  • 7,565
  • 18
  • 56
  • 82
  • 5
    Looks good... what are the values in the 'splited' array? – npinti Oct 26 '11 at 06:56
  • 2
    Your code does indeed work as-is. See [code run live at IdeOne.com](https://ideone.com/KSQboC). – Basil Bourque Oct 12 '18 at 18:46
  • @BasilBourque - I couldn't find any run button on that link – nanosoft Jan 09 '20 at 08:27
  • 2
    @nanosoft The page at IdeOne.com runs automatically upon loading. See output below the code, in *stdout* section. To alter the code, click the `fork` link near top left corner. – Basil Bourque Jan 09 '20 at 08:48
  • Does this answer your question? [How do I split a string with any whitespace chars as delimiters?](https://stackoverflow.com/questions/225337/how-do-i-split-a-string-with-any-whitespace-chars-as-delimiters) – scai Feb 13 '20 at 15:06

17 Answers17

816

What you have should work. If, however, the spaces provided are defaulting to... something else? You can use the whitespace regex:

str = "Hello I'm your String";
String[] splited = str.split("\\s+");

This will cause any number of consecutive spaces to split your string into tokens.

A Jar of Clay
  • 5,622
  • 6
  • 25
  • 39
corsiKa
  • 81,495
  • 25
  • 153
  • 204
  • what regular expression to use if we have to split on these space , + - / ; –  Dec 30 '15 at 13:48
  • I'm not sure off the top of my head. If it's only space, you can form your own class by bracketing it, so in your case probably (note, this is untested) `[ +\\-/;]+` - notice the `\\` around the `-` to escape it. Now, this will probably match `This is+a+ - + - + - test` into 4 tokens, which may or may not be desired. The real problem is you can't use `\\s` to match "any whitespace". You might be better off not using split, and just using `Matcher m = Pattern.compile("([A-Za-z0-9]+)").matcher(text); while(m.find()) list.add(m.group(1));` to fetch words instead of splitting a big text. – corsiKa Dec 30 '15 at 16:27
  • @FarazAhmad Note that those are just off the top of my head, there could be little bugs, so don't copy/paste the code in that comment :) – corsiKa Dec 30 '15 at 16:28
  • string.split("\\s+")[0] - gets only the first part – Combine Nov 24 '16 at 19:54
  • @Combine while that's true, I'd recommend against it - often you need the rest of the array too, and I'd hate for someone to be like `for(int i = 0; i < 4; i++) System.out.println(string.split("\\s+")[i]);` or something silly like that. I'd rather see `String[] splited = string.split("\\s+"); String first = splited[0];` – corsiKa Nov 24 '16 at 20:59
  • Be aware that compiling regex is costly. It is better to generate the pattern upfront. (see gjain's example). – Jotschi Mar 20 '17 at 11:06
  • @Jotschi That's known as a "microoptimization" - I would not be the least concerned that it's too expensive until you've identified that it is so. – corsiKa Mar 21 '17 at 15:54
  • 1
    I find it useful as my use case was to split the string and remove multiple spaces. One line of code does both for me. – Niharika Upadhyay Jul 10 '18 at 09:06
  • What If I want to have `List` as a result (cause in general we should prefer `List` to arrays). Of course I can convert, but can I parse directly to `List` avoiding intermediate array? – Oleg Vazhnev Dec 24 '18 at 21:50
  • @javapowered I wish I had a Christmas present for you. But I don't. Your best bet is `Arrays.asList(str.split("\\s+"));` - or maybe `Stream.of(str.split("\\s+"))` and do something with the stream. – corsiKa Dec 25 '18 at 05:46
  • be aware that for Kotlin you need to use `"\\s+".toRegex()` – user924 Nov 19 '21 at 09:56
135

While the accepted answer is good, be aware that you will end up with a leading empty string if your input string starts with a white space. For example, with:

String str = " Hello I'm your String";
String[] splitStr = str.split("\\s+");

The result will be:

splitStr[0] == "";
splitStr[1] == "Hello";
splitStr[2] == "I'm";
splitStr[3] == "Your";
splitStr[4] == "String";

So you might want to trim your string before splitting it:

String str = " Hello I'm your String";
String[] splitStr = str.trim().split("\\s+");

[edit]

In addition to the trim caveat, you might want to consider the unicode non-breaking space character (U+00A0). This character prints just like a regular space in string, and often lurks in copy-pasted text from rich text editors or web pages. They are not handled by .trim() which tests for characters to remove using c <= ' '; \s will not catch them either.

Instead, you can use \p{Blank} but you need to enable unicode character support as well which the regular split won't do. For example, this will work: Pattern.compile("\\p{Blank}", UNICODE_CHARACTER_CLASS).split(words) but it won't do the trim part.

The following demonstrates the problem and provides a solution. It is far from optimal to rely on regex for this, but now that Java has 8bit / 16bit byte representation, an efficient solution for this becomes quite long.

public class SplitStringTest
{
    static final Pattern TRIM_UNICODE_PATTERN = Pattern.compile("^\\p{Blank}*(.*)\\p{Blank}$", UNICODE_CHARACTER_CLASS);
    static final Pattern SPLIT_SPACE_UNICODE_PATTERN = Pattern.compile("\\p{Blank}", UNICODE_CHARACTER_CLASS);

    public static String[] trimSplitUnicodeBySpace(String str)
    {
        Matcher trimMatcher = TRIM_UNICODE_PATTERN.matcher(str);
        boolean ignore = trimMatcher.matches(); // always true but must be called since it does the actual matching/grouping
        return SPLIT_SPACE_UNICODE_PATTERN.split(trimMatcher.group(1));
    }

    @Test
    void test()
    {
        String words = " Hello I'm\u00A0your String\u00A0";
        // non-breaking space here --^ and there -----^

        String[] split = words.split(" ");
        String[] trimAndSplit = words.trim().split(" ");
        String[] splitUnicode = SPLIT_SPACE_UNICODE_PATTERN.split(words);
        String[] trimAndSplitUnicode = trimSplitUnicodeBySpace(words);

        System.out.println("words: [" + words + "]");
        System.out.println("split: [" + Arrays.stream(split).collect(Collectors.joining("][")) + "]");
        System.out.println("trimAndSplit: [" + Arrays.stream(trimAndSplit).collect(Collectors.joining("][")) + "]");
        System.out.println("splitUnicode: [" + Arrays.stream(splitUnicode).collect(Collectors.joining("][")) + "]");
        System.out.println("trimAndSplitUnicode: [" + Arrays.stream(trimAndSplitUnicode).collect(Collectors.joining("][")) + "]");
    }
}

Results in:

words: [ Hello I'm your String ]
split: [][Hello][I'm your][String ]
trimAndSplit: [Hello][I'm your][String ]
splitUnicode: [][Hello][I'm][your][String]
trimAndSplitUnicode: [Hello][I'm][your][String]
GaspardP
  • 4,217
  • 2
  • 20
  • 33
  • Thanks for this detailed answer. I was running into an exception because of leading and trailing spaces. – ninja Jul 11 '20 at 08:56
32

I do believe that putting a regular expression in the str.split parentheses should solve the issue. The Java String.split() method is based upon regular expressions so what you need is:

str = "Hello I'm your String";
String[] splitStr = str.split("\\s+");
mskfisher
  • 3,291
  • 4
  • 35
  • 48
rbrtl
  • 791
  • 1
  • 6
  • 23
15

Use Stringutils.split() to split the string by whites paces. For example StringUtils.split("Hello World") returns "Hello" and "World";

In order to solve the mentioned case we use split method like this

String split[]= StringUtils.split("Hello I'm your String");

when we print the split array the output will be :

Hello

I'm

your

String

For complete example demo check here

Kh.Taheri
  • 946
  • 1
  • 10
  • 25
sandeep vanama
  • 689
  • 8
  • 8
12

Try

String[] splited = str.split("\\s");

http://download.oracle.com/javase/tutorial/essential/regex/pre_char_classes.html

Vladimir
  • 9,683
  • 6
  • 36
  • 57
8

if somehow you don't wanna use String split method then you can use StringTokenizer class in Java as..

    StringTokenizer tokens = new StringTokenizer("Hello I'm your String", " ");
    String[] splited = new String[tokens.countTokens()];
    int index = 0;
    while(tokens.hasMoreTokens()){
        splited[index] = tokens.nextToken();
        ++index;
    }
Muhammad Suleman
  • 2,892
  • 2
  • 25
  • 33
  • There is a possibility of throwing ArrayIndexOutofBounds Exception. – Ajay Takur Aug 12 '14 at 12:54
  • 3
    No, this won't throw "ArrayIndexOutofBounds" because i have declare array size according to number of tokens found in String. this will make sure that arrays size won't be more than received tokens in a string. – Muhammad Suleman Aug 13 '14 at 07:08
7

Try this one

    String str = "This is String";
    String[] splited = str.split("\\s+");

    String split_one=splited[0];
    String split_second=splited[1];
    String split_three=splited[2];

   Log.d("Splited String ", "Splited String" + split_one+split_second+split_three);
sachin pangare
  • 1,527
  • 15
  • 11
7

OK, so we have to do splitting as you already got the answer I would generalize it.

If you want to split any string by spaces, delimiter(special chars).

First, remove the leading space as they create most of the issues.

str1 = "    Hello I'm your       String    ";
str2 = "    Are you serious about this question_  boy, aren't you?   ";

First remove the leading space which can be space, tab etc.

String s = str1.replaceAll("^\\s+","");//starting with whitespace one or more

Now if you want to split by space or any special char.

String[] sa = s.split("[^\\w]+");//split by any non word char

But as w contains [a-zA-Z_0-9] ,so if you want to split by underscore(_) also use

 String[] sa = s.split("[!,? ._'@]+");//for str2 after removing leading space
Anuj Kumar Soni
  • 192
  • 2
  • 7
5

An alternative way would be:

import java.util.regex.Pattern;

...

private static final Pattern SPACE = Pattern.compile(" ");
String[] arr = SPACE.split(str); // str is the string to be split

Saw it here

gjain
  • 4,468
  • 5
  • 39
  • 47
4

You can separate string using the below code:

   String theString="Hello world";

   String[] parts = theString.split(" ");

   String first = parts[0];//"hello"

   String second = parts[1];//"World"
programandoconro
  • 2,378
  • 2
  • 18
  • 33
Syed Danish Haider
  • 1,334
  • 11
  • 15
3

Very Simple Example below:

Hope it helps.

String str = "Hello I'm your String";
String[] splited = str.split(" ");
var splited = str.split(" ");
var splited1=splited[0]; //Hello
var splited2=splited[1]; //I'm
var splited3=splited[2]; //your
var splited4=splited[3]; //String
BaxD
  • 31
  • 4
2

Since it's been a while since these answers were posted, here's another more current way to do what's asked:

List<String> output = new ArrayList<>();
try (Scanner sc = new Scanner(inputString)) {
    while (sc.hasNext()) output.add(sc.next());
}

Now you have a list of strings (which is arguably better than an array); if you do need an array, you can do output.toArray(new String[0]);

daniu
  • 14,137
  • 4
  • 32
  • 53
2

Not only white space, but my solution also solves the invisible characters as well.

str = "Hello I'm your String";
String[] splited = str.split("\p{Z}");
logbasex
  • 1,688
  • 1
  • 16
  • 22
1

Here is a method to trim a String that has a "," or white space

private String shorterName(String s){
        String[] sArr = s.split("\\,|\\s+");
        String output = sArr[0];

        return output;
    }
Mr T
  • 1,409
  • 1
  • 17
  • 24
0

Simple to Spit String by Space

    String CurrentString = "First Second Last";
    String[] separated = CurrentString.split(" ");

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

         if (i == 0) {
             Log.d("FName ** ", "" + separated[0].trim() + "\n ");
         } else if (i == 1) {
             Log.d("MName ** ", "" + separated[1].trim() + "\n ");
         } else if (i == 2) {
             Log.d("LName ** ", "" + separated[2].trim());
         }
     }
Jaydeep Dobariya
  • 465
  • 6
  • 12
0

Join solutions in one!

public String getFirstNameFromFullName(String fullName){
    int indexString = fullName.trim().lastIndexOf(' ');
    return (indexString != -1)  ? fullName.trim().split("\\s+")[0].toUpperCase() : fullName.toUpperCase();
}
0

Single quotes for char instead of double

String[] splited = str.split(' ');
Ben Call
  • 976
  • 1
  • 10
  • 16