计算 NSString 中大写字母和数字的出现次数



在PHP中,我使用以下代码...

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

。计算密码中大写字母和数字出现的次数。

在目标 C 中,这相当于什么?

您可以使用以下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++;
}

这可以使用 NSStringNSCharacterSet 的能力相当简洁地完成,而不需要手动迭代。

需要递减 1,因为 componentsSeparatedByCharactersInSet: 将始终返回至少一个元素,并且该元素不会计算您的分离。

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

原始答案:虽然您提供的代码不会涵盖所有基础,但如果您出于安全/风险原因需要继续使用这些正则表达式,您可以在下面这样做。

你可以在 Objective-C 中使用 RegEx。节省手动循环访问字符串,并保持代码简洁。这也意味着,由于您不是手动迭代,因此您可能会获得性能提升,因为您可以让编译器/框架编写器对其进行优化。

// Testing string
NSString* password = @"dhdjGHSJD7d56dhHDHa7d5bw3/%£hDJ7hdjs464525";
NSRegularExpression* capitalRegex = [NSRegularExpression regularExpressionWithPattern:@"[A-Z]"
                                                                              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);

最新更新