如何在以下方法中停止ArgumentOutOfRangeException

本文关键字:ArgumentOutOfRangeException 方法 | 更新日期: 2023-09-27 17:57:50

当我尝试使用ArgumentOutOfRangeException来测试字符串是否包含数字和字母以外的字符时,下面的代码会给出ArgumentOut OfRangeException。

考虑到我用注释标记的线将超过最后一个索引的边界,我想这是有道理的。我如何解决这个问题,因为我不可能从(I-1,I)或(I,I)开始。请提供建议。谢谢

public static bool LegalString(string s)
        {
            string dict = "abcdefghijklmnopqrstuvwxyz0123456789";
            for (int i = 0; i < s.Length; i++)
            {
                if (!dict.Contains(s.Substring(i, 1).ToLower()))
                {
                    Console.WriteLine("'" + s.Substring(i, i + 1).ToLower() + "'");//Line that is giving the error
                    return false;
                }
            }
            return true;
        }

编辑:

if (!LegalString(name))
            {
                MessageBox.Show("Invalid Entry for name. Enter only numbers and alphabets.");
            }

我正在使用上面的方法。如果我输入一个名称,例如:Sam.,它会很好用

例如,如果我输入Sam///,当我期望消息框出现时,它将返回异常。

如何在以下方法中停止ArgumentOutOfRangeException

您可以完全避免循环,并使用内置函数来测试字母或数字,如下所示:

public static bool LegalString(string s) {
    if (!s.All(Char.IsLetterOrDigit)) {
        Console.WriteLine( "'{0}'", s.First(c => !Char.IsLetterOrDigit(c)));
        return false;
    }
    return true;        
}

请注意,内置函数允许dict字符串中不包含的其他字母数字字符。如果不希望这样做,可以插入自己的函数来检查各个字符的正确性。

这一行中的i + 1是问题所在:

Console.WriteLine("'" + s.Substring(i, i + 1).ToLower() + "'");//Line that is giving the error

如果您试图显示不在比较字符串中的子字符串,则需要将行更改为:

Console.WriteLine("'" + s.Substring(i, 1).ToLower() + "'");//Line that is giving the error

编辑:

我修改了您的方法,使其具有以下内容,并且它可以像预期的那样使用输入字符串"Sam//"。即返回false:

public static bool LegalString(string s)
{
    string dict = "abcdefghijklmnopqrstuvwxyz0123456789";
    for (int i = 0; i < s.Length; i++)
    {
        if (!dict.Contains(s.Substring(i, 1).ToLower()))
        {
            return false;
        }
    }
    return true;
}

顺便说一句,每次您可以编写这样的函数时,请仔细查看dict

bool IsValidChar(char c)
{
  return char.IsDigit(c) || (c>='a' && c<='z') || (c>='A' && c<='Z');
}

您可以使用正则表达式来代替。。。

private static bool ContainsNonAlphanumeric(string s)
{
    Regex pattern = new Regex(@"'W|_");
    if(pattern.IsMatch(s))
    {
        return true;
    }
    return false;
}

看看这把小提琴。。。http://dotnetfiddle.net/g2YAT0

Console.WriteLine("'" + s.Substring(i, i + 1).ToLower() + "'")行的预期输出是什么。这就是错误,您需要一个长度为i+1的子字符串。我不这么认为。也许应该是s。Lenght-I,只有1。看看吧。

相关文章:
  • 没有找到相关文章