Skip to content

Instantly share code, notes, and snippets.

@hirad
Created July 8, 2015 00:47
Show Gist options
  • Save hirad/b77a6497a0b26f39728e to your computer and use it in GitHub Desktop.
Save hirad/b77a6497a0b26f39728e to your computer and use it in GitHub Desktop.
LHL W2D2 In Class Example
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
NSError* error = nil;
NSString* textString = [NSString stringWithContentsOfFile:@"/path/to/some/file.txt"
encoding:NSUTF8StringEncoding
error:&error];
if (textString == nil) {
NSLog(@"Something went wrong with reading the file: %@", error);
}
NSUInteger wordCount = 0;
NSCharacterSet* separators = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSArray* words = [textString componentsSeparatedByCharactersInSet:separators];
wordCount = [words count];
NSLog(@"There are %lu words in this file.", wordCount);
NSMutableDictionary* listOfWords = [NSMutableDictionary dictionary];
NSCharacterSet* trimmedCharacters = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
for (NSString* w in words) {
NSString* word = [w stringByTrimmingCharactersInSet:trimmedCharacters];
NSNumber* currentCount = [listOfWords objectForKey:word];
if (currentCount == nil) {
listOfWords[word] = @1;
}
else {
listOfWords[word] = @([currentCount integerValue] + 1);
}
}
NSLog(@"Counts by word: \n%@", listOfWords);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment