Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting number of occurrences of characters from array in string?

Tags:

c#

algorithm

I'm writing code to determine whether a password contains enough punctuation characters.

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

Something along these lines:

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.

like image 935
Kev Avatar asked May 22 '13 09:05

Kev


4 Answers

How do I count the number of occurences of any characters from a set?

var count = password.Count(nonAlphaNumericCharSet.Contains);
like image 85
I4V Avatar answered Oct 13 '22 04:10

I4V


you can count like this

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

it will return 3.

Using linq

int count="he!l!l!o".Count(x => x == '!');
like image 45
Mogli Avatar answered Oct 13 '22 03:10

Mogli


Here's 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();
}
like image 1
Carra Avatar answered Oct 13 '22 04:10

Carra


what about a RegExp

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

4=min not word/digit char

8= min password leght

Linq may be considered elegant (it isn't IMHO) but at which performance cost?

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

if you want to match a subset of chars you have to replace \W with []

[]= range of chars

some chars have to be escaped with \

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

there you can find a regular expression cheat sheet

like image 1
giammin Avatar answered Oct 13 '22 03:10

giammin