Splitting a string by space removes line breaks… here is a solution to the problem.
Splitting a string by space removes line breaks
I’m splitting a string with spaces, but for some reason the newline is removed. For example:
String[] splitSentence = "Example sentence\n\n This sentence is an example".
split("\\s+");
splitSentence will contain the following:
["Example", "sentence", "This", "sentence", "is", "an", "example"]
If I do:
String[] splitSentence = "Example sentence\n\n This sentence is an example".
split("\\s");
splitSentence will contain the following:
["Example", "sentence", "", "", "This", "sentence", "is", "an", "example"]
I’m trying to achieve something like this:
["Example", "sentence\n\n", "This", "sentence", "is", "an", "example"]
Or like this:
["Example", "sentence", "\n", "\n", "This", "sentence", "is", "an", "example"]
I’ve tried a lot of things but have no luck… Any help would be appreciated.
Solution
String[] splitSentence = "Example sentence\n\n This sentence is an example".
split(' ');
This version should work, so only white space will be removed instead of new lines.