C#System.IndexOutOfRangeException:索引超出数组范围

问题描述:

获取未处理的异常:System.IndexOutOfRangeException:索引位于数组边界之外。在写评论的线上。该程序将分隔符添加到只知道结束位置的单词中。在单词尝试添加null!=之后没有任何内容时得到错误,但它没有帮助。我明白为什么它发生的原因,但不能来解决C#System.IndexOutOfRangeException:索引超出数组范围

static void Find(ref string line, string sep, out string z) 
{ 
    z = ""; 

    string[] words = line.Split(sep.ToCharArray()); 
    string[] NeedToBeChecked = new string[words.Length]; 
    int a = 0; 
    for (int i = 0; i < words.Length; i++) 
    { 
     if (TikSkaitmenys(words[i]) == true) 
     { 
      NeedToBeChecked[a] = words[i]; 
      a++; 
     } 
    } 
    string LongestWord = ""; 
    int temp = 0; 
    for (int i = 0; i < NeedToBeChecked.Length; i++) 
    { 
     if (NeedToBeChecked[i] != null) 
     { 
      if (NeedToBeChecked[i].Length > temp) 
      { 
       temp = NeedToBeChecked[i].Length; 
       LongestWord = NeedToBeChecked[i]; 
      } 
     } 
    } 
    z = LongestWord; 
    int[] indexarray = new int[50]; 
    int index = 0; 
    int position = 0; 
    int endposition = 0; 
    string word = ""; 
    if (LongestWord != "" && LongestWord != null) 
    { 
     do 
     { 
      index = line.IndexOf(LongestWord, index); 

      if (index != -1) 
      { 
       if (index != 0) 
       { 
        if ('.' == line[index - 1] || ',' == line[index - 1] || ' ' == line[index - 1]) 
        { 
         position = index; 

         endposition = LongestWord.Length + index; 
         while (position != endposition) 
         { 
          word += line[position++]; 
         } 
        } 
       } 
       if (index == 0) 
       { 
        position = index; 

        endposition = LongestWord.Length + index; 
        while (index != endposition) 
        { 
         word += line[index++]; 
        } 
       } 
       index++; 
      } 
     } while (index != -1); 
     while (!Char.IsLetterOrDigit(line[endposition])) // get Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array. 
     { 
      word += line[endposition]; 
      endposition++; 
     } 
    } 

    z = word; 
} 

如果我正确地读你的代码,你只需要检查该指数对字符串的长度。

while (endposition < line.Length && !Char.IsLetterOrDigit(line[endposition]) )