Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections.Generic;
- using System.Linq;
- namespace TableParser
- {
- public class FieldsParserTask
- {
- public static List<string> ParseLine(string line)
- {
- if (line.Length == 0)
- return new List<string> { };
- else if (!line.Contains("\"") && !line.Contains("'"))
- return line.Trim().Split(' ').ToList();
- else
- {
- var fields = new List<string>();
- var i = 0;
- while (i < (line.Trim()).Length)
- {
- var field = ReadField(line.Trim(), i);
- fields.Add(field.Value);
- i += field.Length;
- }
- return fields;
- }
- }
- public static Token QuotesOrNotQuotes(string line, int startIndex, char closeChar)
- {
- var str = "";
- var backslash = 0;
- var newStartIndex = startIndex + 1; //чтобы кавычки не вошли в поле
- while (newStartIndex < line.Length && line[newStartIndex] != closeChar)
- {
- //ищем слеши
- if (line[newStartIndex] == '\\')
- {
- backslash++;
- newStartIndex++; //т к \\ = \
- }
- str = str + line[newStartIndex];
- newStartIndex++;
- }
- return new Token(str, startIndex, str.Length + backslash + 2); //т к мы вручную убирали кавычки
- }
- public static Token QuotesOrNotQuotesInside(string line, int startIndex)
- {
- var str = "";
- var backslash = 0;
- var index = startIndex;
- var closeChars = "\'\"".ToCharArray();
- while (index < line.Length && !closeChars.Contains(line[index]))
- {
- if (line[startIndex] == '\\')
- {
- backslash++;
- index++;
- }
- str = str + line[index];
- index++;
- }
- return new Token(str, index, str.Length + backslash);
- }
- private static Token ReadField(string line, int startIndex)
- {
- if (line[startIndex] == '\"')
- return QuotesOrNotQuotes(line, startIndex, '\"');
- else if (line[startIndex] == '\'')
- return QuotesOrNotQuotes(line, startIndex, '\'');
- else
- return QuotesOrNotQuotesInside(line, startIndex);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement