Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a string by a space without removing the space?

Tags:

string

c#

split

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"]

like image 349
LunchMarble Avatar asked Nov 20 '11 03:11

LunchMarble


People also ask

How do you split a string according to spaces?

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.

How do you remove unwanted space from a string?

Use JavaScript's string. replace() method with a regular expression to remove extra spaces. The dedicated RegEx to match any whitespace character is \s .

Does string split remove whitespace?

Split method, which is not to trim white-space characters and to include empty substrings.


3 Answers

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.

like image 178
svick Avatar answered Sep 27 '22 18:09

svick


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();
} 
like image 27
FailedDev Avatar answered Sep 27 '22 18:09

FailedDev


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", "." }

like image 36
phatfingers Avatar answered Sep 27 '22 19:09

phatfingers