LunchMarble
LunchMarble

Reputation: 5141

Splitting a string by a space without removing the space?

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

Answers (3)

phatfingers
phatfingers

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

svick
svick

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

FailedDev
FailedDev

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

Related Questions