Something like: How to split String with some separator but without removing that separator in Java?
I need to take "Hello World" and get ["Hello", " ", "World"]
The standard solution to split a string is using the split() method provided by the String class. It accepts a regular expression as a delimiter and returns a string array. To split on any whitespace character, you can use the predefined character class \s that represents a whitespace character.
Use JavaScript's string. replace() method with a regular expression to remove extra spaces. The dedicated RegEx to match any whitespace character is \s .
Split method, which is not to trim white-space characters and to include empty substrings.
You can use Regex.Split()
for this. If you enclose the pattern in capturing parentheses, it will be included in the result too:
Regex.Split("Hello World", "( )")
gives you exactly what you wanted.
You can use a regex, although it probably is an overkill :
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();
}
If you split on just the word-boundary, you'll get something very close to what you ask.
string[] arr = Regex.Split("A quick brown fox.", "\\b");
arr[] = { "", "A", " ", "quick", " ", "brown", " ", "fox", "." }
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