Skip to content

Instantly share code, notes, and snippets.

@Zhukn1
Last active August 29, 2015 14:12
Show Gist options
  • Save Zhukn1/a4b11ec90dcf13c3124c to your computer and use it in GitHub Desktop.
Save Zhukn1/a4b11ec90dcf13c3124c to your computer and use it in GitHub Desktop.
Count the number of letter occurrences in a given string.
//initial string
NSString *str = @"the quick brown fox jumped over the fence";
//convert string to array of characters
NSMutableArray *stringArray = [NSMutableArray array];
[str enumerateSubstringsInRange:NSMakeRange(0, str.length)
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
[stringArray addObject:[substring lowercaseString]];
}];
//make an array of unique characters sorted alphabetically
NSArray *letterArray = [[[NSSet setWithArray:stringArray] allObjects] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
//find the number of occurences
[letterArray enumerateObjectsUsingBlock:^(NSString *letter, NSUInteger idx, BOOL *stop) {
NSInteger occurrences = [[stringArray indexesOfObjectsPassingTest:^(NSString *obj, NSUInteger idx, BOOL *stop) {
return [[obj lowercaseString] isEqualToString:[letter lowercaseString]];
}] count];
NSLog(@"letter %@, %@ times", [letter lowercaseString], @(occurrences));
}];
// , 7 times
// b, 1 times
// c, 2 times
// d, 1 times
// e, 6 times
// f, 2 times
// h, 2 times
// i, 1 times
// j, 1 times
// k, 1 times
// m, 1 times
// n, 2 times
// o, 3 times
// p, 1 times
// q, 1 times
// r, 2 times
// t, 2 times
// u, 2 times
// v, 1 times
// w, 1 times
// x, 1 times
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment