获取未处理的异常:System.IndexOutOfRangeException:索引超出了数组的范围。在写评论的行上。程序将分隔符添加到只知道结束位置的单词。在单词尝试添加null!=之后没有任何内容时获取错误,但它没有帮助。我理解它发生的原因但无法找到解决方案
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;
}
答案 0 :(得分:0)
如果我正确读取您的代码,您只需要根据字符串的长度检查索引。
while ( endposition < line.Length && !Char.IsLetterOrDigit(line[endposition]) )