Currently I am splitting a string by spaces. However there are some double spaces that I want to preserve when I put them all back together. Any suggestions on how to do this?
I.e. the string "I went to the beach. I ate pie" is getting split as
I
went
to
the
beach.
I
ate
pie
I don’t want the blank entries but I want to put it back together to the same format. Thanks all!
Do a String replaceAll(” “, ” unlikelyCharacterSequence”) and then split your string by spaces as normal. Then you can convert back to a double space by replacing your {unlikelyCharacterSequence} with ” ” at the end.
However: this will fail if you ever encounter your “unlikely” character sequence in your actual, unmodified String. For a more general purpose solution, check the alternative listed below this example.
Example (warning, depends on non-existance of !@#!@# :
Alternatively you could take a more robust strategy of recombining the string as you have it in your question but ignoring elements containing only a single space: