0

I want to split a String, using " " but .split() gives me empty strings in the array, which I don't want.

I tried this:

String[] arr = "     hello       world!     b   y    e   ".split(" ",0);

Output:

["", "", "", "", "", "hello" and so on....

Expected Output:

["hello","world!","b","y","e"]

How can I achieve this?

1 Answer 1

7

First, trim the string, then split by one or more whitespace (\s+).

String string = "     hello       world!     b   y    e   ";
String[] arr = string.trim().split("\\s+");
// output: ["hello", "world!", "b", "y", "e"]

String.split() reference

Java regular expressions reference

Sign up to request clarification or add additional context in comments.

3 Comments

FYI: Without the trim() call, the result would be ["", "hello", "world!", "b", "y", "e"]. The trimming is use to eliminate the first empty string in the result. The split() method automatically eliminates the ending "" value, that would be present is called with -1 as second parameter.
@user3706706 The + in the regex pattern passed to split eliminates repeating spaces.
@user3706706 And then the .split("\\s+") splits the trimmed string by consecutive spaces.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.