简体   繁体   中英

Counting number of occurrences of characters from array in string?

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.

如何计算集合中任何字符的出现次数?

var count = password.Count(nonAlphaNumericCharSet.Contains);

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 == '!');

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();
}

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

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