using System.Collections.Generic;
using NUnit.Framework;
using NUnit.Framework.Legacy;
namespace TableParser;
[TestFixture]
public class FieldParserTaskTests
{
public static void Test(string input, string[] expectedResult)
{
var actualResult = FieldsParserTask.ParseLine(input);
Assert.AreEqual(expectedResult.Length, actualResult.Count);
for (int i = 0; i < expectedResult.Length; ++i)
{
Assert.AreEqual(expectedResult[i], actualResult[i].Value);
}
}
[TestCase("hello", new[] { "hello" })]
[TestCase("hello world", new[] { "hello", "world" })]
[TestCase(" a b ", new[] { "a", "b" })]
[TestCase("'a b'", new[] { "a b" })]
[TestCase("\"a 'b' c\"", new[] { "a 'b' c" })]
[TestCase("'' \"\"", new[] { "", "" })]
[TestCase(@"'a\'b'", new[] { "a'b" })]
[TestCase(@"\", new[] { @"\" })]
[TestCase(@"\a", new[] { @"\a" })]
[TestCase(@"\\", new[] { @"\" })]
[TestCase(@"""a\""b""", new[] { @"a""b" })]
[TestCase("a\"b c d\"e", new[] { "a", "b c d", "e" })]
[TestCase("", new string[0])]
[TestCase(" ", new string[0])]
public void TestParseLine(string input, string[] expectedResult)
{
Test(input, expectedResult);
}
}
public class FieldsParserTask
{
public static List<Token> ParseLine(string line)
{
var tokens = new List<Token>();
var position = 0;
while (position < line.Length)
{
position = SkipSpaces(line, position);
if (position >= line.Length)
break;
var token = ReadNextToken(line, position);
tokens.Add(token);
position = token.GetIndexNextToToken();
}
return tokens;
}
private static int SkipSpaces(string line, int startIndex)
{
var index = startIndex;
while (index < line.Length && line[index] == ' ')
{
index++;
}
return index;
}
private static Token ReadNextToken(string line, int startIndex)
{
if (line[startIndex] == '\'' || line[startIndex] == '"')
{
return ReadQuotedField(line, startIndex);
}
return ReadField(line, startIndex);
}
private static Token ReadField(string line, int startIndex)
{
var length = 0;
while (startIndex + length < line.Length)
{
var currentChar = line[startIndex + length];
if (currentChar == ' ' || currentChar == '\'' || currentChar == '"')
break;
length++;
}
return new Token(line.Substring(startIndex, length), startIndex, length);
}
public static Token ReadQuotedField(string line, int startIndex)
{
return QuotedFieldTask.ReadQuotedField(line, startIndex);
}
}