How to count the number of uppercase characters in a NSString?

狂风中的少年 提交于 2019-12-21 19:27:29

问题


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.


回答1:


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.




回答2:


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




回答3:


One line solution

 NSUInteger count = [[[@"A string HERE!!" componentsSeparatedByCharactersInSet:[[NSCharacterSet uppercaseLetterCharacterSet] invertedSet]] componentsJoinedByString:@""] length]; // count = 5


来源:https://stackoverflow.com/questions/7141545/how-to-count-the-number-of-uppercase-characters-in-a-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!