Advertisement
vilenskass

Untitled

Oct 17th, 2019
485
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using NUnit.Framework;
  7.  
  8. namespace TableParser
  9. {
  10.     [TestFixture]
  11.     public class QuotedFieldTaskTests
  12.     {
  13.         [TestCase("''", 0, "", 2)]
  14.         [TestCase("'a'", 0, "a", 3)]
  15.         [TestCase("\'\'", 0, "", 2)]
  16.         [TestCase("\'a\'", 0, "a", 3)]
  17.         [TestCase(@"some text ""QF \"""" other text", 10, "QF \"", 7)]
  18.         [TestCase("\"a", 0, "a", 2)]
  19.         public void Test(string line, int startIndex, string expectedValue, int expectedLength)
  20.         {
  21.             var actualToken = QuotedFieldTask.ReadQuotedField(line, startIndex);
  22.             Assert.AreEqual(new Token(expectedValue, startIndex, expectedLength), actualToken);
  23.         }
  24.     }
  25.  
  26.     class QuotedFieldTask
  27.     {
  28.         public static Token ReadQuotedField(string line, int startIndex)
  29.         {
  30.             var result = new StringBuilder();
  31.             var whatQuote = line[startIndex];
  32.             var lastQuote = line.LastIndexOf(whatQuote);
  33.             var endIndex = lastQuote;
  34.             if (lastQuote == 0 || lastQuote == startIndex)
  35.             {
  36.                 lastQuote = line.Length - 1;
  37.                 endIndex = lastQuote + 1;
  38.             }
  39.             var deltaIndex = lastQuote - startIndex;
  40.             line = DeleteSlashes(line, startIndex, endIndex);
  41.             return new Token(line, startIndex, deltaIndex + 1);
  42.         }
  43.  
  44.         public static string DeleteSlashes(string line, int startIndex, int endIndex)
  45.         {
  46.             var result = new StringBuilder();
  47.             for (var i = startIndex + 1; i < endIndex; i++)
  48.             {
  49.                 if (line[i] == '\\')
  50.                 {
  51.                     if (line[i + 1] == '\"' || line[i + 1] == '\'' || line[i + 1] == '\\')
  52.                     {
  53.                         result.Append(line[i + 1]);
  54.                         i++;
  55.                     }
  56.                 }
  57.                 else result.Append(line[i]);
  58.             }
  59.  
  60.             return result.ToString();
  61.         }
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement