I would like to check if a NSString contains each digit possible (0-9) more then 5 times. I do not need to know which digit or how many times, I simply want it to return TRUE or False for whether any of the digits are contained more then 5 times in the string. I would like it to be as efficient as possible.
I have given it some thought and the long way of going about it would be to place all 10 digits (again 0-9) in an array and then loop through each digit comparing it to the string. If there are more than 5 matches within the string, place a flag that will return true.
Can anyone tell me if there is a "better" or more efficient way of going about this problem?
Thank you!
This code tries to be as performant as possible.
BOOL checkDigits(NSString *string)
{
// get the raw UTF-16 code fragments, hopefully without a copy
const UniChar *characters = CFStringGetCharactersPtr((__bridge CFStringRef)string);
NSData *characterData = nil;
if (characters == NULL) {
characterData = [string dataUsingEncoding:NSUTF16StringEncoding];
characters = [characterData bytes];
}
// initialize 10 individual counters for digits
int digitCount[10] = {};
NSUInteger length = [string length];
// loop over the characters once
for (NSUInteger i = 0; i != length; ++i) {
UniChar c = characters[i];
// UTF-16 encodes ASCII digits as their values
if (c >= '0' && c <= '9') {
int idx = c - '0';
if (digitCount[idx] == 4)
return YES;
digitCount[idx] += 1;
}
}
// keep the NSData object alive until here
[characterData self];
return NO;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments