Last active
August 29, 2015 14:12
-
-
Save Zhukn1/a4b11ec90dcf13c3124c to your computer and use it in GitHub Desktop.
Count the number of letter occurrences in a given string.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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