Skip to content

Instantly share code, notes, and snippets.

@hebertialmeida
Created February 2, 2014 14:35
Show Gist options
  • Save hebertialmeida/8769297 to your computer and use it in GitHub Desktop.
Save hebertialmeida/8769297 to your computer and use it in GitHub Desktop.
Finding the most common character in a string
- (NSString *)mostCommonCharacter:(NSString *)string
{
__block NSMutableArray *charIndex = [[NSMutableArray alloc] init];
// Enumerate
[string enumerateSubstringsInRange:NSMakeRange(0, string.length) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop)
{
[charIndex addObject:substring];
}];
// Count
NSCountedSet *counter = [[NSCountedSet alloc] initWithArray:charIndex];
NSString *mostCommon;
NSUInteger highest = 0;
for (NSString *s in counter) {
if ([counter countForObject:s] > highest) {
highest = [counter countForObject:s];
mostCommon = s;
}
}
return mostCommon;
}
// Demo
- (void)viewDidLoad
{
NSLog(@"mostCommon: %@", [self mostCommonCharacter:@"aaaabbbaaaa * bbbccccccccdd ddddddd dddd"]);
// this returns -> d
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment