使用 C# 检查给定密码中至少 1 个介于 0-9 之间的数字

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

我正在尝试循环遍历字符串中的每个字符,以查看它们是否是 0-9 之间的数字。我收到 numCheck 数组的索引越界错误,所以我知道我的问题是当我尝试 运行 时,IDE 期望 txt_Pass.Text 的长度为 =我的数组中的字符数。这是错误的,但我不确定如何解决。我是否需要使用矢量,因为我不确定输入密码的长度?还是我完全不在了?

        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;
        }

'''

遇到任何超过十个字符的字符串的数组索引问题,因为您遍历所有这些值并使用该迭代索引也可以查看 numCheck 数组。 因为它只有十个元素,所以访问第 11 个是不行的。

一种天真的方法是使用两个 嵌套 循环来检查 numCheck 中的任何字符是否等于输入字符串中的任何字符,例如(这可以稍微优化一下,但我没有打扰,因为正如您将在下面发现的那样,这是完全没有必要的)

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 :-)

但是,如前所述,当 C# 提供了各种奇妙的库函数来为您完成繁重的工作时,这并不是真正必要的:

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

总而言之,您的整个代码块可以缩减为:

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

LINQ 来拯救!

var numCheck = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
lbl_Form1_NumError.Visible = txt_Pass.Text.Any(c => numCheck.Contains(c));

正则表达式来拯救!

using System.Text.RegularExpressions;

lbl_Form1_NumError.Visible = Regex.IsMatch(txt_Pass.Text, @"\d")

我认为最简单的解决方案结合了 LINQ 的 Any and Char.IsDigit:

lbl_Form1_NumError.Visible = !txt_Pass.Text.Any(char.IsDigit);