Reputation: 5141
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"]
Upvotes: 6
Views: 3038
Reputation: 10250
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", "." }
Upvotes: 1
Reputation: 244827
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.
Upvotes: 16
Reputation: 26930
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();
}
Upvotes: 1