简体   繁体   中英

Check if string contains at least two alpha chars

I need to check if a string has at least two alpha characters, like a1763r or ab1244
I was thinking I would use something like:

myString = "a123B";  
myString.Any(char.IsDigit).Count();

but I'm using .net 2.0 so this method Any() does not exists.

Is there something equivalent?

Don't know about alpha or what not, but you can count how many characters are digits without Linq like so:

string str = "a123B";
int digits = 0;
foreach (char c in str)
    if (char.IsDigit(c))
        digits++;
print(digits); // 3

You can create a simple helper function that loops over your string, taking in a minimum threshold to meet. It returns boolean to match the type of output behavior from .Any()

public bool ContainsMinAlphaCharacters(string input, int threshold)
{
    var count = 0;
    foreach (var character in input)
    {
        if (char.IsDigit(character)) count++;
        if (count >= threshold) 
        {
            return true;
        }
    }

    return false;
}

Use regexpressions

two letters: Regex.IsMatch(myString, "[A-Za-z].*?[A-Za-z]");

two digits: Regex.IsMatch(myString, "\\d.*?\\d");

Not really. You will have to loop through the string and check if each character is a digit to get the count.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM