Counting the number of capital letters and numbers in NSString

In PHP, I use the following code ...

$passwordCapitalLettersLength = strlen(preg_replace("![^AZ]+!", "", $password)); $passwordNumbersLength = strlen(preg_replace("/[0-9]/", "", $password)); 

... to count how many times uppercase letters and numbers are displayed in a password.

What is equivalent to this in Objective-C?

+4
source share
2 answers

You can use NSCharacterSet :

 NSString *password = @"aas2dASDasd1asdASDasdas32D"; int occurrenceCapital = 0; int occurenceNumbers = 0; for (int i = 0; i < [password length]; i++) { if([[NSCharacterSet uppercaseLetterCharacterSet] characterIsMember:[password characterAtIndex:i]]) occurenceCapital++; if([[NSCharacterSet decimalDigitCharacterSet] characterIsMember:[password characterAtIndex:i]]) occurenceNumbers++; } 
+7
source

This can be done quite briefly using the capabilities of NSString and NSCharacterSet , instead of having to iterate manually.

A reduction of 1 is required since componentsSeparatedByCharactersInSet: will always return at least one element and that one element will not count your partitions.

 NSString* password = @"dhdjGHSJD7d56dhHDHa7d5bw3/%£hDJ7hdjs464525"; NSArray* capitalArr = [password componentsSeparatedByCharactersInSet:[NSCharacterSet uppercaseLetterCharacterSet]]; NSLog(@"Number of capital letters: %ld", (unsigned long) capitalArr.count - 1); NSArray* numericArr = [password componentsSeparatedByCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]]; NSLog(@"Number of numeric digits: %ld", (unsigned long) numericArr.count - 1); 

Original answer: Until the code that you provided covers all the databases, if you need to continue using these regular expressions for security / risk reasons, you can do this below.

You can use RegEx in Objective-C. Saves iteration manually through String and keeps the code concise. It also means that you do not iterate manually, you can get a performance boost as you can enable the compiler / framework optimizer.

 // Testing string NSString* password = @"dhdjGHSJD7d56dhHDHa7d5bw3/%£hDJ7hdjs464525"; NSRegularExpression* capitalRegex = [NSRegularExpression regularExpressionWithPattern:@"[AZ]" options:0 error:nil]; NSRegularExpression* numbersRegex = [NSRegularExpression regularExpressionWithPattern:@"[0-9]" options:0 error:nil]; NSLog(@"Number of capital letters: %ld", (unsigned long)[capitalRegex matchesInString:password options:0 range:NSMakeRange(0, password.length)].count); NSLog(@"Number of numeric digits: %ld", (unsigned long)[numbersRegex matchesInString:password options:0 range:NSMakeRange(0, password.length)].count); 
+1
source

Source: https://habr.com/ru/post/1447527/


All Articles