I am looking to split a string into an array of strings at every single space.
For example:
This_sentence_gets__split.
(Underscores represent spaces here)
Becomes
"This"
"sentence"
"gets"
" "
(note the double space was left as one space)
"split."
I assume I can do this with String.split(String regex)
but I am not very good with regular expressions and I do not know how I would accomplish this.
Edit:
Any spaces after the first should be split into substrings as well. For example:
Split___this.
becomes "Split
" "
" "
"this."
I think this might be what you are looking for (you can improve it with \\s
class for all whitespace like tabs, new lines and so on)
String data = "This_sentence__gets___split".replace('_', ' ');
// System.out.println(data);
String arr[] = data.split("(?<! ) |(?<= {2})");
for (String s : arr)
System.out.println("\"" + s + "\"");
Output:
"This"
"sentence"
" "
"gets"
" "
" "
"split."
Explanation:
"(?<! ) "
will split only on spaces that don't have space before it"(?<= {2})"
will split in place that have two spaces before it.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