This may not be the "best" way of doing things but it was the most fun way of doing it for me and it takes quite good advantage of Foundation using characters sets, counted sets and block based string enumeration.
// Your string
NSString *myString = @"he11o 12345 th1s 55 1s 5 very fun 55 1ndeed.";
// A set of all numeric characters
NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
NSUInteger digitThreshold = 5;
// An emtpy counted set
NSCountedSet *numberOccurances = [NSCountedSet new];
// Loop over all the substrings as composed characters
// this will not have the same issues with e.g. Chinese characters as
// using a C string would. (Available since iOS 4)
[myString enumerateSubstringsInRange:NSMakeRange(0, myString.length)
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
// Check if substring is part of numeric set of characters
if ([substring rangeOfCharacterFromSet:numbers].location != NSNotFound) {
[numberOccurances addObject:substring];
// Check if that number has occurred more than 5 times
if ([numberOccurances countForObject:substring] > digitThreshold) {
*stop = YES;
// Do something here based on that fact
NSLog(@"%@ occured more than %d times", substring, digitThreshold);
}
}
}];
If you don't let it stop then it will continue to count the number of occurrences for all the digits in that string.
If you log the counted set is looks like this (number within square brackets are count):
<NSCountedSet: 0xa18d830> (3 [1], 1 [6], 4 [1], 2 [1], 5 [6])