How do you split a string of words and retain whitespaces?
Here is the code:
String words[] = s.split(" ");
String s contains: hello world
After the code runs, words[] contains: "hello"
""
world
Ideally, it should not be an empty string in the middle, but contain both whitespaces: words[] should be: "hello"
" "
" "
world
How do I get it to have this result?
To split a string keeping the whitespace, call the split() method passing it the following regular expression - /(\s+)/ . The regular expression uses a capturing group to preserve the whitespace when splitting the string.
The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
Answer: You just have to pass (“”) in the regEx section of the Java Split() method. This will split the entire String into individual characters.
String. Split can use multiple separator characters. The following example uses spaces, commas, periods, colons, and tabs as separating characters, which are passed to Split in an array . The loop at the bottom of the code displays each of the words in the returned array.
You could use lookahead/lookbehind assertions:
String[] words = "hello world".split("((?<=\\s+)|(?=\\s+))");
where (?<=\\s+)
and (?=\\s+)
are zero-width groups.
If you can tolerate both white spaces together in one string, you can do
String[] words = s.split("\\b");
Then words contains ("hello", " ", "world")
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With