Reputation: 123
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
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"]
Java regular expressions reference
Upvotes: 7