Ronak Chaniyara
Ronak Chaniyara

Reputation: 5436

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.

Upvotes: 0

Views: 85

Answers (2)

vadian
vadian

Reputation: 285150

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

Upvotes: 3

Phillip Mills
Phillip Mills

Reputation: 31016

If you really want to use a NSCharacterSet, there's characterSetWithCharactersInString for building a custom one. I'm not sure there's any advantage compared to just looping over the string with ==, though.

Upvotes: 1

Related Questions