Advertisement
Guest User

Untitled

a guest
Oct 27th, 2016
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.35 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace TableParser
  5. {
  6. public class FieldsParserTask
  7. {
  8. // При решении этой задаче постарайтесь избежать создания методов, длиннее 10 строк.
  9. // Ниже есть метод ReadField — это подсказка. Найдите класс Token и изучите его.
  10. // Подумайте как можно использовать ReadField и Token в этой задаче.
  11. public static List<string> ParseLine(string line)
  12. {
  13. int i = 0;
  14. List<string> fields = new List<string> { };
  15. while (i < line.Length)
  16. {
  17. Token token = ReadField(line, i);
  18. fields.Add(token.Value);
  19. if (i == token.GetIndexNextToToken())
  20. {
  21. break;
  22. }
  23. i = token.GetIndexNextToToken()+Strip(line, token.GetIndexNextToToken());
  24.  
  25. }
  26. return fields;
  27. }
  28.  
  29.  
  30. private static Token ReadField(string line, int startIndex)
  31. {
  32. bool insideBlock = (line[startIndex] == '\'' || line[startIndex] == '"');
  33. int startIndex_ = insideBlock ? startIndex : startIndex;
  34. if (insideBlock)
  35. {
  36. return ParseInsideBlock(line, startIndex_, line[startIndex]);
  37. }else
  38. {
  39. return ParseOutsideBlock(line, startIndex_);
  40. }
  41. }
  42.  
  43. private static Token ParseOutsideBlock(string line, int startIndex)
  44. {
  45. int i = startIndex;
  46. string accum = "";
  47. while (i<line.Length)
  48. {
  49. if(line[i] == '\'' || line[i] == '"' || line[i] == ' ')
  50. {
  51. break;
  52. }
  53. accum += line[i];
  54. i++;
  55. }
  56. return new Token(accum, startIndex, i-startIndex);
  57. }
  58.  
  59.  
  60.  
  61. private static Token ParseInsideBlock(string line, int startIndex, char blockSymbol)
  62. {
  63. bool escape = false;
  64. string accum = "";
  65. int i = startIndex + 1;
  66. while(i<line.Length)
  67. {
  68. if(line[i] == blockSymbol && !escape)
  69. {
  70. break;
  71. }
  72. Tuple<string,bool> tup = Escaping(line[i], escape);
  73. accum += tup.Item1;
  74. escape = tup.Item2;
  75. i++;
  76. }
  77. return new Token(accum, startIndex, (i-startIndex)+1);
  78. }
  79.  
  80. private static Tuple<string, bool> Escaping(char c, bool escape)
  81. {
  82. if (c == '\\' && !escape)
  83. {
  84. return Tuple.Create<string, bool>("", true);
  85. }else
  86. {
  87. return Tuple.Create<string, bool>(c.ToString(), false);
  88. }
  89. }
  90.  
  91. private static int Strip(string line, int startIndex)
  92. {
  93.  
  94. int i = startIndex;
  95. if (i>=line.Length||line[i] != ' ')
  96. {
  97. return 0;
  98. }
  99. else
  100. {
  101. while (line[i] == ' ' && i < line.Length) { i++; }
  102. return i - startIndex;
  103. }
  104. }
  105. }
  106. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement