如何在NSString中找到特定字符的出现次数是大写的?

时间:2016-08-29 13:08:11

标签: ios objective-c iphone nsstring uppercase

有没有办法在NSString中找到任何特定字符的大写字母,例如:

NSString *str=@"How many U's are in Uppercase";

我尝试的是给出所有大写字符,

int count=0;  
for (i = 0; i < [str length]; i++) {
    BOOL isUppercase = [[NSCharacterSet uppercaseLetterCharacterSet] characterIsMember:[str characterAtIndex:i]];
    if (isUppercase == YES)
       count++;
}

OR

[[str componentsSeparatedByCharactersInSet:[NSCharacterSet uppercaseLetterCharacterSet]] count] - 1;

但是我需要NSString中任何特定字符的大写字母出现。

2 个答案:

答案 0 :(得分:3)

您可以使用正则表达式执行此操作:

NSString *str = @"How many U's are in Uppercase";
NSString *pattern = @"U";
NSRegularExpression *expression = [[NSRegularExpression alloc] initWithPattern:pattern options:0 error:nil];
NSArray *result = [expression matchesInString:str options:0 range:NSMakeRange(0, str.length)];
NSLog(@"%ld", result.count); // 2

答案 1 :(得分:1)

如果您真的想使用NSCharacterSet,则可以使用characterSetWithCharactersInString来构建自定义的==。我不确定与使用 <configSections> <section name="MySQL" type="MySql.Data.MySqlClient.MySqlConfiguration, MySql.Data, Version=6.7.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"/> </configSections> <MySQL> <Replication> <ServerGroups> <Group name="MasterSlave"> <Servers> <Server name="master" IsMaster="true" connectionstring=" server=<server>;port=<port>;uid=<user>;password=<password>;"/> <Server name="slave" IsMaster="false" connectionstring=" server=<server>;port=<port>;uid=<user>;password=<password>;"/> </Servers> </Group> </ServerGroups> </Replication> </MySQL> 循环字符串相比有什么优势。