How to count the number of uppercase characters in

2019-04-10 04:15发布

I'm trying to find out the best way to count the number of uppercase characters that are in a NSString. I know how to find out if a certain character is uppercase by using this code:

NSString *s = @"This is a string";
BOOL isUppercase = [[NSCharacterSet uppercaseLetterCharacterSet] characterIsMember:[s characterAtIndex:0]];

What would be the best way to count the number of uppercase letters in a NSString? Thanks.

3条回答
forever°为你锁心
2楼-- · 2019-04-10 05:00

One line solution

 NSUInteger count = [[[@"A string HERE!!" componentsSeparatedByCharactersInSet:[[NSCharacterSet uppercaseLetterCharacterSet] invertedSet]] componentsJoinedByString:@""] length]; // count = 5
查看更多
男人必须洒脱
3楼-- · 2019-04-10 05:01
NSString *s = @"This is a string";  
int count=0;  
for (i = 0; i < [s length]; i++) {
    BOOL isUppercase = [[NSCharacterSet uppercaseLetterCharacterSet] characterIsMember:[s characterAtIndex:i]];
    if (isUppercase == YES)
       count++;
}

count is the number of uppercase occurences.

查看更多
SAY GOODBYE
4楼-- · 2019-04-10 05:03

Walk through the indices in the string one by one and add 1 to a counter whenever you find an uppercase letter.

查看更多
登录 后发表回答