Counting the number of occurrences of characters from an array in a string?

I am writing code to determine if the password contains enough punctuation characters.

How to count the number of occurrences of any characters from a set?

Something like that:

private const string nonAlphaNumericCharSet = "#*!?£$+-^<>[]~()&"; ... public static bool PasswordMeetsStrengthRequirements(string password) { return password.Length >= MINIMUM_PASSWORD_LENGTH && password.NumberOfOccurences(nonAlphaNumericCharSet.ToCharArray()) >= MINIMUM_NONALPHANUMERIC_CHARS; } 

Bonus points for an elegant linq solution.

+7
source share
4 answers

How to count the number of occurrences of any characters from a set?

 var count = password.Count(nonAlphaNumericCharSet.Contains); 
+17
source

you can count it

 int count = "he!l!l!o".Split('!').Length - 1; 

he will return 3.

Using linq

 int count="he!l!l!o".Count(x => x == '!'); 
+1
source

Here is an example:

 private const string nonAlphaNumericCharSet = "#*!?£$+-^<>[]~()&"; public static bool PasswordMeetsStrengthRequirements(string password) { return password.Count(x => nonAlphaNumericCharSet.Contains(x)) > 2 && password.Length > 1; } public static void Main() { PasswordMeetsStrengthRequirements("Test").Dump(); PasswordMeetsStrengthRequirements("Test#").Dump(); PasswordMeetsStrengthRequirements("(Test#").Dump(); PasswordMeetsStrengthRequirements("(Te[st#").Dump(); } 
+1
source

how about regexp

 Regex rgx = new Regex(@"^(?=.*(\W.*){4,}).{8,}$", RegexOptions.Compiled); bool validPassword = rgx.IsMatch(password); 

4 = min not word / digit char

8 = minimum password

Linq can be considered elegant (it's not IMHO), but at what cost?

------------ Update after comment ---------------

if you want to match a subset of characters, you must replace \W with []

[] = character range

some characters must be escaped with \

in your case: [#\*!\?£\$\+-\^\<\>\[\]~\(\)&]

you can find a regex charter

+1
source

All Articles