Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections.Generic;
- using NUnit.Framework;
- 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("text", new []{"text"})]
- [TestCase("hello world", new[] {"hello","world"})]
- [TestCase(" hello world ", new[] {"hello", "world"})]
- [TestCase("hello", new[] {"hello"})]
- [TestCase(" hello world ", new[] {"hello", "world"})]
- [TestCase("a 'bcd ef' 'x y'", new[] {"a","bcd ef","x y"})]
- [TestCase("' ", new [] {" "})]
- [TestCase("\"a 'b' 'c' d\"", new [] {"a 'b' 'c' d"})]
- [TestCase(@"'a ""b"" ""c"" d'", new [] {"a \"b\" \"c\" d"})]
- [TestCase("\"ab\"с", new [] {"ab","с"})]
- [TestCase(@"""\\""", new[] { "\\" })]
- [TestCase("", new string[0])]
- [TestCase("'a b'", new[] { "a b" })]
- [TestCase(@"""", new[] {""})]
- [TestCase("'\\\'a\\\''", new[]{"'a'"})]
- [TestCase("\"\\\"a\\\"\"", new []{"\"a\""})]
- public static void RunTests(string input, string[] expectedOutput)
- {
- // Тело метода изменять не нужно
- Test(input, expectedOutput);
- }
- }
- public class FieldsParserTask
- {
- // При решении этой задаче постарайтесь избежать создания методов, длиннее 10 строк.
- // Подумайте как можно использовать ReadQuotedField и Token в этой задаче.
- public static List<Token> ParseLine(string line)
- {
- var tokensList = new List<Token>();
- if (line[0] == '\"' || line[0] == '\'')
- tokensList.Add(ReadQuotedField(line, 0));
- else
- {
- var token = ReadField(line, 0);
- if (token.Value.Trim() != "")
- tokensList.Add(token);
- }
- while (tokensList[tokensList.Count - 1].GetIndexNextToToken() < line.Length - 1)
- {
- var index = tokensList[tokensList.Count - 1].GetIndexNextToToken();
- if (line[index] == '\"' || line[index] == '\'')
- tokensList.Add(ReadQuotedField(line, index));
- else
- tokensList.Add(ReadField(line, index));
- }
- for (var i = 0; i < tokensList.Count; i++)
- {
- if (string.IsNullOrEmpty(tokensList[i].Value))
- tokensList.RemoveAt(i);
- }
- return tokensList; // сокращенный синтаксис для инициализации коллекции.
- }
- private static Token ReadField(string line, int startIndex)
- {
- var token = QuotedFieldTask.ReadQuotedField(line, startIndex);
- return new Token(token.Value.Trim(), token.Position, token.Length);
- }
- public static Token ReadQuotedField(string line, int startIndex)
- {
- return QuotedFieldTask.ReadQuotedField(line, startIndex);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement