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?
String.splitremoves the delimiter you provide to it (the space in this case). If you want a different behavior, you'd have to implement a variant ofsplityourself.