[java] How to split a String by space

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.

This question is related to java string split arrays

The answer is



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

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]

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


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+");

you can saperate string using the below code

   String thisString="Hello world";

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

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

    String second = parts[1];//"World"

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

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


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

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


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

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

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

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

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to split

Parameter "stratify" from method "train_test_split" (scikit Learn) Pandas split DataFrame by column value How to split large text file in windows? Attribute Error: 'list' object has no attribute 'split' Split function in oracle to comma separated values with automatic sequence How would I get everything before a : in a string Python Split String by delimiter position using oracle SQL JavaScript split String with white space Split a String into an array in Swift? Split pandas dataframe in two if it has more than 10 rows

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?