Splitting a string with a space without removing the space?

Something like: How to split a String with some separator but not removing that separator in Java?

I need to take "Hello World" and get ["Hello", "," World "]

+6
source share
3 answers

You can use regex, although this is probably brute force:

StringCollection resultList = new StringCollection(); Regex regexObj = new Regex(@"(?:\b\w+\b|\s)"); Match matchResult = regexObj.Match(subjectString); while (matchResult.Success) { resultList.Add(matchResult.Value); matchResult = matchResult.NextMatch(); } 
+1
source

You can use Regex.Split() . If you attach a template to capturing parentheses, it will also be included in the result:

 Regex.Split("Hello World", "( )") 

gives you exactly what you wanted.

+16
source

If you split only at the border of the word, you will get something very close to what you are asking.

  string[] arr = Regex.Split("A quick brown fox.", "\\b"); 

arr [] = {"," A ",", "quick", "," brown ",", "fox", "." }

+1
source

Source: https://habr.com/ru/post/901921/


All Articles