An elegant way to count alphanumeric characters in a string?

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

"Bored," I'm doing it now:

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

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

+5
source share
4 answers

Here's a quick and dirty LINQ way to get letters and numbers:

 password.Count(char.IsLetterOrDigit) 

It is rather a direct copy of what you are doing:

 password.Count(c => !char.IsLetterOrDigit(c)) 
+14
source
 int num = password.Where((t, i) => !char.IsLetterOrDigit(password, i)).Count(); if (num < MinRequiredNonAlphanumericCharacters) return false; 
+2
source

You can do this with a single line of Regex. Whatever is understandable is a moot point.

 num = new Regex(@"\w", RegexOptions.IgnoreCase).Matches(input).Count 
0
source

You can use Take() to make sure you are not checking more letters than necessary:

 int minCount = password.Where(x => !char.IsLetterOrDigit(x)).Take(MinRequired).Count(); if (minCount < MinRequired) { // No good } 

The idea is that we keep checking until you hit the minimum number. At this point, we can stop because we know that we have a valid password. Take() takes as much as it can, and no more than that, so if there are not enough, it will simply return a number less than what you requested.

0
source

All Articles