字符串以“;”结尾时的子串错误要么 ” ”

时间:2016-03-30 12:07:30

标签: c#

编写一个函数,以编译器的代码行形式获取字符串,每当我输入以空格或分号结尾的字符串时(因为每行代码都是用我的语言编写的)我得到以下错误第3行:

  

System.ArgumentOutOfRangeException未处理

     

索引和长度必须指代字符串中的位置。

如果我在最后,我总是收到此错误“;”或“”字符串。例如,如果我输入“a = b;”它将读取a = b部分并将它们放入我的符号表并识别分隔符“=”但是一旦到达“;”就给我一个错误。如果我输入“a = b”(没有分号),它将在第二个“”之后给出错误,而根本不读取“b”。如果我输入2行代码“a = b;”和“c = 1;”它只会在第二行代码后给出错误。

private static void readChar(
    ref int IX, ref string sentence, ref string testChar, ref int inputType)
{
    testChar = sentence.Substring(IX, 1);
    IX++;
    int IX2 = 0;
    int IX3 = 0;

    if ("|*/+-@#$%^&(),`=".Contains(testChar)) 
    {
        inputType = 5;
    } // delimiter

    else if (Char.IsDigit(testChar, IX2)) 
    {
        inputType = 3;
        IX2++;
    } // numeric          

    else if (Char.IsWhiteSpace(testChar, IX3)) 
    {
        inputType = 6;
        IX3++;
     } // space

    else if (testChar == ";") 
    {
        inputType = 7;
    } // semicolon          
    else 
    {
        inputType = 1;
    } // end alpha
}

调用readChar的示例代码:

switch (inputType)
            {
                case 1: // alpha
                    {
                        convertCharToInt(ref inputChar, ref X);
                        wordTotal = wordTotal + X;
                        word = word + inputChar;
                        readChar(ref sentenceIX, ref sentence, ref inputChar, ref inputType);

                        while ((inputType != inputBreakChar) & (inputType != inputDelimeter) & (inputType != inputSemiColon)) //(inputType == 1)
                        {
                            convertCharToInt(ref inputChar, ref X);
                            wordTotal = wordTotal + X;
                            word = word + inputChar;
                            readChar(ref sentenceIX, ref sentence, ref inputChar, ref inputType);
                        } // end while inputType

                        calcSymbolTableIX(ref symbolTable, ref wordTotal, ref  R);
                        setSymbolTableIX(ref symbolTable, ref symbolTableName, ref word, ref R);

                        word = "";
                        break;
                    } // end case 1

2 个答案:

答案 0 :(得分:2)

你可以添加一个检查,如果这是字符串的结尾

if(IX == sentence.Length - 1 )
   testChar = sentence.Substring(IX);
else if(IX < sentence.Length - 1)
   testChar = sentence.Substring(IX, 1);

答案 1 :(得分:0)

你需要表明你的休息状况;一旦IX到达最后一个角色,如果你在那个时候再尝试一个角色,你将获得所述异常。由于索引是从0开始的,因此您的循环(我假设您已经拥有)必须在IX == sentence.Length时立即停止,而不仅仅在它更大时停止。

除此之外,您对Char.IsDigitChar.IsWhitespace的来电被打破,您需要将0作为第二个参数而不是IX2IX3