Улучшить код разбора аргументов - C#
Формулировка задачи:
Разрабатываю программу, и не хочу использовать костыли и говнокод, но делая одну функцию я встал в тупик:
Функция парсит строку типа: command "argument1 and spaces" argument2 3
И возвращает массив: "command", "argument1 and spaces", "argument2", "3"
Как можно оптимизировать этот код?
public static string[] ParseArgs (string full)
{
if(!full.Contains(" "))
throw new ArgumentException("Args not found", "full");
var args = new Dictionary<int, string>();
var chars = full.ToCharArray();
bool nospace=false;
int index=0;
for(int i=0; i<chars.Length; i++)
{
var ch = chars[i];
if(ch==' ' && !nospace)
index++;
else if(ch=='"')
nospace=!nospace;
else
args[index]+=ch;
}
if(nospace)
throw new Exception("You must close the quotation marks");
var resp = string[args.Count];
for(int i=0; i<args.Count; i++)
{
resp[i] = args[i];
}
return resp;
}Решение задачи: «Улучшить код разбора аргументов»
textual
Листинг программы
using Microsoft.VisualBasic.FileIO;
string rawCmd = "command "argument1 and spaces" argument2 3";
using (StringReader sr = new StringReader(rawCmd))
using (TextFieldParser parser = new TextFieldParser(sr))
{
parser.Delimiters = new string[] { " " };
string[] tokens = parser.ReadFields();
foreach (var s in tokens) Console.WriteLine(s);
}