Search code examples
c#stringsplit

Split sting with white space and don't split if white space is between '


I have a string

string text = "'test string' 'hello world'";

As you see I can't split the string with white space with text.Split

I try that and it actually work. Is there is a simpler way ?

List<string> Splitedtext = new List<string>();
bool InQuotationMark = false;
int Position = 0;

for (int index = 0; index < text.Length; index++) {
   if (text[index] == '\'') { 
      InQuotationMark = !InQuotationMark;
   }

   if (text[index] == ' ' && !InQuotationMark) {
      Splitedtext.Add(text.Substring(Position, index - Position));
      Position = index;
   }

   if (index == text.Length - 1){
      Splitedtext.Add(text.Substring(Position + 1, index - Position));
   }                
}

The Result That I want

'test string'
'hello world'

Solution

  • A non regex approach would be:

    List<string> resultList = text.Split('\'', StringSplitOptions.RemoveEmptyEntries)
            .Where(s => !string.IsNullOrWhiteSpace(s))
            .Select(s => $"'{s}'")
            .ToList();
    

    Demo