Advertisement
Guest User

Untitled

a guest
Oct 21st, 2017
287
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.62 KB | None | 0 0
  1. using System.Collections.Generic;
  2. using System.Linq;
  3.  
  4. namespace TableParser
  5. {
  6. public class FieldsParserTask
  7. {
  8. public static List<string> ParseLine(string line)
  9. {
  10. if (line.Length == 0)
  11. return new List<string> { };
  12. else if (!line.Contains("\"") && !line.Contains("'"))
  13. return line.Trim().Split(' ').ToList();
  14. else
  15. {
  16. var fields = new List<string>();
  17. var i = 0;
  18. while (i < (line.Trim()).Length)
  19. {
  20. var field = ReadField(line.Trim(), i);
  21. fields.Add(field.Value);
  22. i += field.Length;
  23. }
  24. return fields;
  25. }
  26. }
  27.  
  28. public static Token QuotesOrNotQuotes(string line, int startIndex, char closeChar)
  29. {
  30. var str = "";
  31. var backslash = 0;
  32. var newStartIndex = startIndex + 1; //чтобы кавычки не вошли в поле
  33. while (newStartIndex < line.Length && line[newStartIndex] != closeChar)
  34. {
  35. //ищем слеши
  36. if (line[newStartIndex] == '\\')
  37. {
  38. backslash++;
  39. newStartIndex++; //т к \\ = \
  40. }
  41. str = str + line[newStartIndex];
  42. newStartIndex++;
  43. }
  44. return new Token(str, startIndex, str.Length + backslash + 2); //т к мы вручную убирали кавычки
  45. }
  46.  
  47. public static Token QuotesOrNotQuotesInside(string line, int startIndex)
  48. {
  49. var str = "";
  50. var backslash = 0;
  51. var index = startIndex;
  52. var closeChars = "\'\"".ToCharArray();
  53. while (index < line.Length && !closeChars.Contains(line[index]))
  54. {
  55. if (line[startIndex] == '\\')
  56. {
  57. backslash++;
  58. index++;
  59. }
  60. str = str + line[index];
  61. index++;
  62. }
  63. return new Token(str, index, str.Length + backslash);
  64. }
  65.  
  66. private static Token ReadField(string line, int startIndex)
  67. {
  68. if (line[startIndex] == '\"')
  69. return QuotesOrNotQuotes(line, startIndex, '\"');
  70. else if (line[startIndex] == '\'')
  71. return QuotesOrNotQuotes(line, startIndex, '\'');
  72. else
  73. return QuotesOrNotQuotesInside(line, startIndex);
  74. }
  75. }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement