I was thinking about applications with larger amounts of text and I'd rather not have to count my array. For this, I added to the method to get this:
- (NSDictionary *) numberOfLettersNeededFromString:(NSString *)sourceString {
sourceString = [sourceString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
sourceString = [sourceString stringByReplacingOccurrencesOfString:@" " withString:@""];
const char * sourceChars = sourceString.UTF8String;
NSMutableArray * arr = [NSMutableArray new];
for (int i = 0; i < sourceString.length; i++) {
[arr addObject:[NSString stringWithFormat:@"%c", sourceChars[i]]];
}
static NSString * alphabet = @"abcdefghijklmnopqrstuvwxyz";
NSMutableDictionary * masterDictionary = [NSMutableDictionary new];
for (int i = 0; i < alphabet.length; i++) {
NSString * alphabetLetter = [alphabet substringWithRange:NSMakeRange(i, 1)];
NSIndexSet * indexes = [arr indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
if ([[(NSString *)obj lowercaseString] isEqualToString:alphabetLetter]) {
return YES;
}
else {
return NO;
}
}];
masterDictionary[alphabetLetter] = @(indexes.count);
}
return masterDictionary;
}
Run like:
NSDictionary * lettersNeeded = [self numberOfLettersNeededFromString:@"Hello\nI love cat\nI love dog\nI love mommy\nMommy loves daddy"];
NSLog(@"%@", lettersNeeded);
Will give you:
{ a = 2; b = 0; c = 1; d = 4; e = 5; f = 0; g = 1; h = 1; i = 3; j = 0; k = 0; l = 6; m = 6; n = 0; o = 8; p = 0; q = 0; r = 0; s = 1; t = 1; u = 0; v = 4; w = 0; x = 0; y = 3; z = 0; }
Which I think is better if I had a very large amount of text and I just needed to know how many of each letter I would need.