ChemDev
ChemDev

Reputation: 837

Nested NSArray for loop won't loop in nested fashion

I've been learning Objective-C for five days and I have only 2 weeks of prior programming experience so please make answers as simple as possible.

I'm doing an exercise in a book that asks me to generate a list of proper names that are also regular words. To do this I have am running a for loop for each proper name from a NSArray proper name object. Within that for loop I have a nested for loop testing each name against each word in an NSArray regular word object using the caseInsensitiveCompare method.

Here is my code:

import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        //Gets the sting with proper names
        NSString *propername = [NSString stringWithContentsOfFile:@"/usr/share/dict/propernames" encoding:
        NSUTF8StringEncoding error:NULL];

        //Gets the string with regularwords
        NSString *inpropername = [NSString stringWithContentsOfFile:@"/usr/share/dict/words" encoding:
                                NSUTF8StringEncoding error:NULL];

        NSArray *proper = [propername componentsSeparatedByString:@"/n"];
        NSArray *inproper = [inpropername componentsSeparatedByString:@"/n"];

        for (NSString *n in proper){
            NSLog(@"%@", n);
            for(NSString *i in inproper){
                NSLog(@"%@", i);
                if ([n caseInsensitiveCompare:i] == NSOrderedSame)
                {
                    NSLog(@"Yahooo! Got One! %@", n);
                }
            }
        }

    }
    return 0;
}

Instead of the for loops running in a nested fashion they are running in a sequential fashion. The output is like this:

Aaron  
all the names...  
Yvonne  
a  
all the regular words....  
Zyzzogeton  

Any ideas for why the nested for loop is not running in a nested fashion?

Upvotes: 0

Views: 154

Answers (1)

Julien
Julien

Reputation: 3477

The code is correct except you are not breaking the files into words since you are using "/n" instead of "\n".

This means that each array contains exactly one element which is a string with all the words in it.

Upvotes: 4

Related Questions