Ronak Chaniyara Ronak Chaniyara - 3 months ago 10
Objective-C Question

How to find number of occurrences of particular character are in uppercase in NSString?

is there any way to find uppercase occurrences of any particular character in

NSString
, for example:

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


What i tried is giving all Uppercase characters,

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;


But i need uppercase occurrences of any particular character in
NSString
.

Answer

You can do it with regular expression:

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