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

时间:2012-11-21 15:49:25

标签: objective-c nsstring

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

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

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

目标C中的相同内容是什么?

2 个答案:

答案 0 :(得分:7)

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

}

答案 1 :(得分:1)

这可以使用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);