Home > Software engineering >  IndexOutOfRange (IsAllDigits Method)
IndexOutOfRange (IsAllDigits Method)

Time:04-05

I am novice in C# and just learning it. I am sure that you will consider this question dumb but I really can't understand the real reason for the following in the below-mentioned method:

    public static bool CheckIfCharactersAreDigits (string raw)
    {
        string s = raw.Trim();
        if (s.Length == 0) return false;
        for (int index = 0; index <= s.Length; index  )
        {
            if (char.IsDigit(s[index]) == false) return false;
        }
        return true;
    }

Why their is a mistake when in my for loop I write the expression like this: index <= s.length? It always give me an error no matter what characters or numbers I enter. And the error is IndexOutOfRange. When I write this expression like this: index < s.Length; then everything is fine. But why? For instance: I am entering 100 as an argument for string raw and the index of it is [0, 1 , 2] or 3. Why it is an error if index equals to any argument of string raw (with the exception of something containing only white space or spaces)?
If it bothers you I am getting the argument for string raw via Console.ReadLine() if it somehow valuable info (not sure about that).

Thanks in advance for any suggestions! It really bothers me...

CodePudding user response:

You are iterating one index to much. If the size of your array is 10 for example, the index of the last item will be 9.

So you need to change your loop condition from

index <= s.Length

to

index < s.Length

For loops for arrays (and other standard collections as well) should therefore always look like this:

for (int i = 0; i < array.Length; i  )
{

}

CodePudding user response:

In order to get rid pesky out of range errors (here index <= s.Length instead of index < s.Length) try either quering with a help of Linq:

using System.Linq;

...

public static bool CheckIfCharactersAreDigits (string raw)
{
    //DONE: public method arguments validation (note null case)
    if (string.IsNullOrWhiteSpace(raw))
       return false;

    return raw.Trim().All(c => char.IsDigit(c));  
}

or use foreach loop: just let .net do all the work with indexes for you:

public static bool CheckIfCharactersAreDigits (string raw)
{
    //DONE: public method arguments validation (note null case)
    if (string.IsNullOrWhiteSpace(raw))
       return false;

    foreach (char c in raw.Trim())
      if (!char.IsDigit(c))
        return false;

    return true;  
}
  • Related