Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- namespace TableParser
- {
- public class FieldsParserTask
- {
- // При решении этой задаче постарайтесь избежать создания методов, длиннее 10 строк.
- // Ниже есть метод ReadField — это подсказка. Найдите класс Token и изучите его.
- // Подумайте как можно использовать ReadField и Token в этой задаче.
- public static List<string> ParseLine(string line)
- {
- int i = 0;
- List<string> fields = new List<string> { };
- while (i < line.Length)
- {
- Token token = ReadField(line, i);
- fields.Add(token.Value);
- if (i == token.GetIndexNextToToken())
- {
- break;
- }
- i = token.GetIndexNextToToken()+Strip(line, token.GetIndexNextToToken());
- }
- return fields;
- }
- private static Token ReadField(string line, int startIndex)
- {
- bool insideBlock = (line[startIndex] == '\'' || line[startIndex] == '"');
- int startIndex_ = insideBlock ? startIndex : startIndex;
- if (insideBlock)
- {
- return ParseInsideBlock(line, startIndex_, line[startIndex]);
- }else
- {
- return ParseOutsideBlock(line, startIndex_);
- }
- }
- private static Token ParseOutsideBlock(string line, int startIndex)
- {
- int i = startIndex;
- string accum = "";
- while (i<line.Length)
- {
- if(line[i] == '\'' || line[i] == '"' || line[i] == ' ')
- {
- break;
- }
- accum += line[i];
- i++;
- }
- return new Token(accum, startIndex, i-startIndex);
- }
- private static Token ParseInsideBlock(string line, int startIndex, char blockSymbol)
- {
- bool escape = false;
- string accum = "";
- int i = startIndex + 1;
- while(i<line.Length)
- {
- if(line[i] == blockSymbol && !escape)
- {
- break;
- }
- Tuple<string,bool> tup = Escaping(line[i], escape);
- accum += tup.Item1;
- escape = tup.Item2;
- i++;
- }
- return new Token(accum, startIndex, (i-startIndex)+1);
- }
- private static Tuple<string, bool> Escaping(char c, bool escape)
- {
- if (c == '\\' && !escape)
- {
- return Tuple.Create<string, bool>("", true);
- }else
- {
- return Tuple.Create<string, bool>(c.ToString(), false);
- }
- }
- private static int Strip(string line, int startIndex)
- {
- int i = startIndex;
- if (i>=line.Length||line[i] != ' ')
- {
- return 0;
- }
- else
- {
- while (line[i] == ' ' && i < line.Length) { i++; }
- return i - startIndex;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement