-2

Getting Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array. on the line that is written a comment. The program adds the separators to the word knowing only the end position. Get the error when there is nothing after the word tried adding null != , but it didn't help. I understand the reason why it is happening but can't come to a solution

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;
}
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
yehofinivu
  • 1
  • 1
  • 4

1 Answers1

0

If I'm reading your code correctly, you just need to check the index against the length of the string.

while ( endposition < line.Length && !Char.IsLetterOrDigit(line[endposition])  )
Chris Berger
  • 557
  • 4
  • 14