Sorry in advance for this being such a beginner question. Here are the steps of what I’m trying to do:
- Read two text files (unix word list files for proper names and
regular words) - Separate the text into string
- Place the separated strings into an array for each list
- Compare the arrays and count the number of matches
For whatever reason, this code continually returns null matches. What might I be doing? Thanks a ton for any help.
int main (int argc, const char * argv[])
{
@autoreleasepool {
// Place discrete words into arrays for respective lists
NSArray *regularwords = [[NSString stringWithContentsOfFile:@"/usr/dict/words" encoding:NSUTF8StringEncoding error:NULL] componentsSeparatedByString:@"\n"];
NSArray *propernames = [[NSString stringWithContentsOfFile:@"/usr/dict/propernames" encoding:NSUTF8StringEncoding error:NULL] componentsSeparatedByString:@"\n"];
// The compare and count loop
NSInteger *counter;
for (int i = 0; i < [propernames count]; i++) {
NSString *stringFromRegularWords = [regularwords objectAtIndex:i];
NSString *properNamesString = [propernames objectAtIndex:i];
if ([properNamesString isEqualToString:stringFromRegularWords]) {
counter++;
}
}
// Print the number of matches
NSLog(@"There was a total of %@ matching words", counter);
}
return 0;
}
You’re doing
objectAtIndex:i, expecting the words to be in exactly same indexes in both files. What you should probably do is add entries from one of the files to an NSMutableSet and then check for membership that way.Note that my example also uses “fast enumeration,” i.e. the
for ... insyntax. While not necessary to solve your problem, it does make the code shorter and arguably faster.