Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to count alphanumeric chars in a string?

I am looking for an elegant way, preferably a short linq expression, to count how many alphanumeric chars a given string contains.

The 'boring' way I do it now is this:

int num = 0;
for (int i = 0; i < password.Length; i++)
{
    if (!char.IsLetterOrDigit(password, i))
    {
        num++;
    }
}
if (num < MinRequiredNonAlphanumericCharacters)
    return false;

This is rather short already, but I am sure with some linq magic this can be done in an even shorter, equally understandable expression, right?

like image 401
magnattic Avatar asked Jul 19 '12 21:07

magnattic


2 Answers

Here's the quick and dirty LINQ way to get the letter & digit count:

password.Count(char.IsLetterOrDigit)

This is more of a direct copy of what you're doing:

password.Count(c => !char.IsLetterOrDigit(c))
like image 102
Austin Salonen Avatar answered Sep 20 '22 18:09

Austin Salonen


int num = password.Where((t, i) => !char.IsLetterOrDigit(password, i)).Count();

if (num < MinRequiredNonAlphanumericCharacters)
    return false;
like image 31
HatSoft Avatar answered Sep 21 '22 18:09

HatSoft