c# lastindexof 抛出异常

c# lastindexof throwing an exception

我不确定为什么会抛出异常。这段代码应该获取光标位置然后获取 space 的最后一个索引或输入以挑选最后一个单词 typed.It 有时会抛出超出范围的异常。选择起始值是否会高于字符串中的字符数?我不确定到底是什么原因造成的。我放置 if 语句是为了避免对不存在的字符进行索引……但这并没有以某种方式改善或恶化它。

        private string word()
    {
        char[] array1 = { '\n', ' ' };
        int end = textBox1.SelectionStart;
        int strt = 0;
        if (textBox1.Text.LastIndexOfAny(array1)!=-1)
        {
             strt = textBox1.Text.LastIndexOfAny(array1,end);
        }



        if (strt==-1) { strt = 0; }

        return textBox1.Text.Substring(strt, end - strt);

    }

通常,当 startIndex 指定的位置不在此实例中时,您会遇到此异常。

因此,检查您的情况下的 end 值并确保它小于 textBox1.Text.Length

根据 MSDN,

String.LastIndexOfAny Method (Char[], Int32) Reports the zero-based index position of the last occurrence in this instance of one or more characters specified in a Unicode array. The search starts at a specified character position and proceeds backward toward the beginning of the string.

在您的情况下,textBox1.SelectionStart 将为您提供光标在文本框中的当前位置。假设 TextBox 中的字符串为 "sampl",并且光标位于文本的末尾,因此 SelectionStart 将为您提供值 5。请注意,框中的字符串长度为 5,但它在索引 5 处没有字符,因为它遵循基于 0 的索引。

因此,在访问此代码 strt = textBox1.Text.LastIndexOfAny(array1,end); 时,5 不是字符串中的有效索引。这会导致此处出现错误。

所以使用下面几行来获取光标位置(end),那么你的代码就会如你所愿

int end = 0;
if (textBox1.Text.Length > 1)
    end = textBox1.SelectionStart - 1;

尝试将第一个 LastIndexOfAny() 调用存储到局部变量中,然后从 end 中减去它以获得对 LastIndexOfAny().

的第二次调用的值
private string word()
{
    char[] array1 = { '\n', ' ' };
    int end = textBox1.SelectionStart;
    int strt = 0;
    var lastIndex = textBox1.Text.LastIndexOfAny(array1);
    if (lastIndex !=-1)
    {
         strt = textBox1.Text.LastIndexOfAny(array1, end - lastIndex);
    }



    if (strt==-1) { strt = 0; }

    return textBox1.Text.Substring(strt, end - strt);

}