如何检查字符串是否至少包含1个字母字符?

时间:2011-07-26 00:11:51

标签: c# asp.net string random

我的ASP.NET应用程序要求我生成大量随机字符串,每个字符串至少包含1个字母和数字字符,并且整体上应该是字母数字。 为此,我的逻辑是如果随机字符串是数字,则再次生成代码:

        public static string GenerateCode(int length)
        {
            if (length < 2 || length > 32)
            {
                throw new RSGException("Length cannot be less than 2 or greater than 32.");
            }
            string newcode = Guid.NewGuid().ToString("n").Substring(0, length).ToUpper();
            return newcode;
        }

        public static string GenerateNonNumericCode(int length)
        {
            string newcode = string.Empty;
            try
            {
                newcode = GenerateCode(length);
            }
            catch (Exception)
            {
                throw;
            }
            while (IsNumeric(newcode))
            {
                return GenerateNonNumericCode(length);
            }
            return newcode;
        }

        public static bool IsNumeric(string str)
        {
            bool isNumeric = false;
            try
            {
                long number = Convert.ToInt64(str);
                isNumeric = true;
            }
            catch (Exception)
            {
                isNumeric = false;
            }
            return isNumeric;
        }

在调试时,它工作正常但是当我要求它创建10,000个随机字符串时,它无法正确处理它。当我将该数据导出到Excel时,我发现平均至少有20个数字字符串。 这是我的代码或C#的问题? - 我的 如果有人在寻找代码,

public static string GenerateCode(int length)
    {
        if (length < 2)
        {
            throw new A1Exception("Length cannot be less than 2.");
        }
        var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        var random = new Random();
        var result = new string(

        Enumerable.Repeat(chars, length)
                  .Select(s => s[random.Next(s.Length)])
                  .ToArray());

    return result;
}

public static string GenerateAlphaNumericCode(int length)
{
    string newcode = string.Empty;
    try
    {
        newcode = GenerateCode(length);
        while (!IsAlphaNumeric(newcode))
        {
            newcode = GenerateCode(length);
        }
    }
    catch (Exception)
    {
        throw;
    }

    return newcode;
}

public static bool IsAlphaNumeric(string str)
{
    bool isAlphaNumeric = false;
    Regex reg = new Regex("[0-9A-Z]+");
    isAlphaNumeric = reg.IsMatch(str);
    return isAlphaNumeric;
}

感谢您的所有想法。

6 个答案:

答案 0 :(得分:6)

如果你想坚持使用Guid作为生成器,你总是可以使用正则表达式进行验证 如果至少存在一个alpha,则只返回true

Regex reg = new Regex("[a-zA-Z]+");

然后只需使用IsMatch方法查看您的字符串是否有效

这样你就不需要(恕我直言,相当丑陋)try..catch转换。

更新:我看到你后来关于实际使你的代码变慢的评论。您是仅仅实例化Regex对象一次,还是每次进行测试?如果后者那么这将是相当低效的,你应该考虑在你的班级上使用“懒惰”属性,例如。

    private Regex reg;

    private Regex AlphaRegex
    {
        get
        {
            if (reg == null) reg = new Regex("[a-zA-Z]+");
            return reg;
        }
    }

然后在您的方法中使用AlphaRegex.IsMatch()。我希望这会有所作为。

答案 1 :(得分:5)

使用名称空间然后使用System.Linq;使用普通字符串 检查字符串是否包含至少一个字符或数字。

using System.Linq; 

string StrCheck = "abcd123";
check the string has characters --->  StrCheck.Any(char.IsLetter) 

check the string has numbers   --->   StrCheck.Any(char.IsDigit)

if (StrCheck.Any(char.IsLetter) && StrCheck.Any(char.IsDigit))
{
//statement goes here.....
}

sorry for the late reply ...

答案 2 :(得分:2)

我不太明白你想要的字符串除了字母(abc等)之外 - 让我们说数字 您可以生成如下随机字符:

Random r = new Random();
r.Next('a', 'z'); //For lowercase
r.Next('A', 'Z'); //For capitals
//or you can convert lowercase to capital:
char c = 'k' + ('A' - 'a');


如果你想创建一个字符串:

var s = new StringBuilder();
for(int i = 0; i < length; ++i)
    s.Append((char)r.Next('a', 'z' + 1)); //Changed to char
return s.ToString(); 

注意:我不太了解ASP.NET,所以我只是表现得像是C#。

答案 3 :(得分:2)

至少有一个,或一个具体的?

How can I generate random alphanumeric strings in C#?

该问题中有很多解决方案。您可以根据需要调整长度。

答案 4 :(得分:1)

严格地回答你的问题,使用你现有的代码:你的递归逻辑有一个问题,可以通过不使用递归来避免(有绝对没有理由在{{中使用递归) 1}})。请改为:

GenerateNonNumericCode

其他一般说明

您的代码效率非常低 - 抛出异常代价很高,因此在循环中使用try / catch是缓慢且毫无意义的。正如其他人所建议的那样,正则表达式更有意义( public static string GenerateNonNumericCode(int length) { string newcode = GenerateCode(length); while (IsNumeric(newcode)) { newcode = GenerateCode(length); } return newcode; } 命名空间)。

  

我的代码或C#有问题吗?

如果有疑问,问题几乎不会是C#。

答案 5 :(得分:0)

所以,我会将代码更改为:

static Random r = new Random();
public static string GenerateNonNumericCodeFaster(int length) {
    var firstLength = r.Next(0, length - 1);
    var secondLength = length - 1 - firstLength;
    return GenerateCode(firstLength)
         + (char) r.Next((int)'A', (int)'G')
         + GenerateCode(secondLength);
}

您可以按原样保留GenerateCode功能。你要扔掉的其他东西。这里的想法当然是,而不是测试字符串是否包含字母字符,你只需明确地输入一个字符。在我的测试中,使用此代码可以在0.0172963秒内生成10,000个8个字符的字符串,而代码需要大约52秒。所以,是的,这大约快了3000倍:)。