Во-первых, вы, очевидно, используете какую-то библиотеку синтаксического анализа, у вас будет больше шансов, если вы изменили свой код, например, на что-то вроде того, что я сделал, чтобы любой мог скопировать, вставить, запустить ваш код.
Ответ прост, ваш (строковый литерал) разбирающий регион не анализирует все входные данные.Вот ваш код, модифицированный для использования без какой-либо дополнительной библиотеки:
public class Test
{
static char ElementAtOrDefault(string value, int position)
{
return position >= value.Length ? default(char) : value[position];
}
static string parseStringLiteral(string value, ref int ChPosition)
{
StringBuilder Value = new StringBuilder();
char ChCurrent = ElementAtOrDefault(value, ++ChPosition);
while (ChCurrent != '"')
{
Value.Append(ChCurrent);
ChCurrent = ElementAtOrDefault(value, ++ChPosition);
if (ChCurrent == '"')
{
// "" sequence only acceptable
if (ElementAtOrDefault(value, ChPosition + 1) == '"')
{
Value.Append(ChCurrent);
// skip 2nd double quote
ChPosition++;
// move position next
ChCurrent = ElementAtOrDefault(value, ++ChPosition);
}
}
else if (default(Char) == ChCurrent)
{
// message: unterminated string
throw new Exception("ScanningException");
}
}
ChPosition++;
return Value.ToString();
}
public static void test(string literal)
{
Console.WriteLine("testing literal with " + literal.Length +
" chars:\n" + literal);
try
{
int pos = 0;
string res = parseStringLiteral(literal, ref pos);
Console.WriteLine("Parsed " + res.Length + " chars:\n" + res);
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
Console.WriteLine();
}
public static int Main(string[] args)
{
test(@"""Hello Language Design""");
test(@"""Is there any problems with the """"strings""""?""");
test(@"""v#:';?325;.<>,|+_)""(*&^%$#@![]{}\|-_=""");
return 0;
}
}
Запуск этой программы приводит к выводу:
testing literal with 23 chars:
"Hello Language Design"
Parsed 21 chars:
Hello Language Design
testing literal with 45 chars:
"Is there any problems with the ""strings""?"
Parsed 41 chars:
Is there any problems with the "strings"?
testing literal with 39 chars:
"v#:';?325;.,|+_)"(*&^%$#@![]{}\|-_="
Parsed 18 chars:
v#:';?325;.,|+_)
Так что это работает для вашего тестирования, но алгоритм неверен,попробуйте выполнить:
//literal with "", should produce ", but it does not
test(@"""""""""");
И вы получите неправильно:
testing literal with 4 chars:
""""
Parsed 0 chars:
Проблема в том, что если вы встречаете символ "в вашем состоянии while, вы не проверяете следующий символ, если он"или нет:
while (ChCurrent != '"') //bug
Конечно, я создал правильную версию для вас :-) Вот она (она использует ваш стиль, только что отредактированная версия ваша):
static string parseStringLiteral(string value, ref int ChPosition)
{
StringBuilder Value = new StringBuilder();
char ChCurrent = ElementAtOrDefault(value, ++ChPosition);
bool goon = true;
while (goon)
{
if (ChCurrent == '"')
{
// "" sequence only acceptable
if (ElementAtOrDefault(value, ChPosition + 1) == '"')
{
Value.Append(ChCurrent);
// skip 2nd double quote
ChPosition++;
// move position next
ChCurrent = ElementAtOrDefault(value, ++ChPosition);
}
else goon = false; //break;
}
else if (default(Char) == ChCurrent)
{
// message: unterminated string
throw new Exception("ScanningException");
}
else
{
Value.Append(ChCurrent);
ChCurrent = ElementAtOrDefault(value, ++ChPosition);
}
}
ChPosition++;
return Value.ToString();
}
Удачного кодирования: -)