For various reasons, I'm parsing a string, this code will explain what I'm after:
string baseString = "This is a \"Very Long Test\"";
string[] strings = baseString.Split(' ');
List<String> stringList = new List<string>();
string temp = String.Empty;
foreach (var s in strings)
{
if (!String.IsNullOrWhiteSpace(temp))
{
if (s.EndsWith("\""))
{
string item = temp + " " + s;
stringList.Add(item.Substring(1,item.Length - 2));
temp = string.Empty;
}
temp = temp + " " + s;
}
else if (s.StartsWith("\""))
{
temp = s;
}
else
{
stringList.Add(s);
}
}
stringList.ForEach(Console.WriteLine);
The output should be:
This
is
a
Very Long Test
Basically, given a string, it will split it on spaces, unless its grouped into speech marks, the same way the command line does it.
Any better way to do this code?
StringBuilder
instead. \$\endgroup\$