Question

Split or Regex.Split is used to extract the word in a sentence(s) and store them in array. I instead would like to extract the spaces in a sentence(s) and store them in array (it is possible that this sentence contains multiple spaces). Is there easy way of doing it? I first tried to split it normally, and then use string.split(theSplittedStrings, StringSplitOptions.RemoveEmptyEntries) however, that did not preserve the amount of spaces that exists.

---------- EDIT -------------

for example. If there is a sentence "This is a test". I would like to make an array of string { " ", " ", " "}.

---------- EDIT END ---------

Any helps are appreciated.

Thank you.

Was it helpful?

Solution 2

This code matches all spaces in the input string and outputs their indexes:

const string sentence = "This  is a test   sentence.";
MatchCollection matches = Regex.Matches(sentence, @"\s");

foreach (Match match in matches)
{
    Console.WriteLine("Space at character {0}", match.Index);
}

This code retrieves all space groups as an array:

const string sentence = "This  is a test   sentence.";
string[] spaceGroups = Regex.Matches(sentence, @"\s+").Cast<Match>().Select(arg => arg.Value).ToArray();

In either case, you can look at the Match instances' Index property values to get the location of the space/space group in the string.

OTHER TIPS

EDIT:

Based on your edited question, I believe you can do that with simple iteration like:

string str = "This is     a  test";

List<string> spaceList = new List<string>();
var temp = str.TakeWhile(char.IsWhiteSpace).ToList();

List<char> charList = new List<char>();
foreach (char c in str)
{

    if (c == ' ')
    {
        charList.Add(c);
    }

    if (charList.Any() && c != ' ')
    {
        spaceList.Add(new string(charList.ToArray()));
        charList = new List<char>();
    }

}

That would give you spaces in different elements of List<string>, if you need an array back then you can call ToArray

(Old Answer) You don't need string.Split. You can count the spaces in the string and then create array like:

int spaceCount = str.Count(r => r == ' ');
char[] array = Enumerable.Repeat<char>(' ', spaceCount).ToArray();

If you want to consider White-Space (Space, LineBreak, Tabs) as space then you can use:

int whiteSpaceCount = str.Count(char.IsWhiteSpace);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top