user3706706
user3706706

Reputation: 123

Java : Split string on same character

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?

Upvotes: 0

Views: 367

Answers (1)

mario_sunny
mario_sunny

Reputation: 1432

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

Upvotes: 7

Related Questions