Search code examples
c#for-looppasswordsindexoutofboundsexception

checking for at least 1 number between 0-9 in a given password using c#


I'm trying to cycle through each char in a string to see if any of them are a number between 0-9. I'm getting an index out of bounds error for the numCheck array, so I know that my issue is that when I attempt to run, the IDE expects the length of txt_Pass.Text to = the number of chars I have in my array. This is wrong, but I'm not sure how to fix it. Would I need to use a vector since I'm not sure how long the input password will be? Or am I totally off?

        char[] numCheck = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

        for (int i = 0; i < txt_Pass.Text.Length; i++)
        {
            if (txt_Pass.Text[i] != numCheck[i])
            {
                lbl_Form1_NumError.Visible = true;
            }
            lbl_Form1_NumError.Visible = false;
        }

'''


Solution

  • You will get an array index problem for any string with more than ten characters, since you iterate over all those values and use that iteration index to look into the numCheck array as well. Since this only has ten elements, accessing the 11th is a no-no.

    A naive approach would be to have two nested loops to check if any character in numCheck is equal to any character of the input string, something like (this could be optimised somewhat but I haven't bothered since, as you'll find out below, it's totally unnecessary)

    bool hasADigit = false;
    for (int i = 0; i < txt_Pass.Text.Length; i++) {
        for (int j = 0; j < numCheck.Length; j++) {
            if (txt_Pass.Text[i] == numCheck[j]) {
                hasADigit = true;
            }
        }
    }
    // hasADigit is true if it, well, has a digit :-)
    

    But, as stated, this isn't really necessary when C# provides all sorts of wondrous library functions to do the heavy lifting for you:

    bool hasADigit = (txt_Pass.Text.indexOfAny(numCheck) != -1);
    

    In summary, your entire code block can be reduced to:

    char[] numCheck = {'0','1','2','3','4','5','6','7','8','9'};
    lbl_Form1_NumError.Visible = (txt_Pass.Text.indexOfAny(numCheck) == -1);