How to split () a string while saving spaces

How do you split a line of words and keep spaces?

Here is the code:

String words[] = s.split(" "); 

String s contains: hello world

After running the code, the words [] contain: "hello" "" world

Ideally, this should not be an empty string in the middle, but contain both spaces: the words [] should be: "hello" " " " " world

How do I get this result?

+7
java regex
source share
4 answers

You can use the lookahead / lookbehind statements:

 String[] words = "hello world".split("((?<=\\s+)|(?=\\s+))"); 

where (?<=\\s+) and (?=\\s+) are groups with zero width.

+10
source share

s.split("((?<= )|(?= ))"); is one way.

Technically, regex uses lookahead and lookbehind. The only space after each = is the delimiter.

+3
source share

You can do something like this:

 List<String> result = new LinkedList<>(); int rangeStart = 0; for (int i = 0; i < s.length(); ++i) { if (Character.isWhitespace(s.charAt(i))) { if (rangeStart < i) { result.add(s.substring(rangeStart, i)); } result.add(Character.toString(s.charAt(i))); rangeStart = i + 1; } } if (rangeStart < s.length()) { result.add(s.substring(rangeStart)); } 

Yes, no regular expressions, judge me. This way you can see how it works more easily.

+1
source share

If you can wrap both spaces together on the same line, you can do

 String[] words = s.split("\\b"); 

Then the words contain ("hello", " ", "world") .

+1
source share

All Articles