0

我已经学习了 Objective-C 5 天,而我只有 2 周的编程经验,所以请尽可能简单地回答。

我在一本书中做一个练习,要求我生成一个专有名称列表,这些专有名称也是常规单词。为此,我为NSArray专有名称对象中的每个专有名称运行了一个 for 循环。在那个 for 循环中,我有一个嵌套的 for 循环,使用该方法针对NSArray常规单词对象中的每个单词测试每个名称。caseInsensitiveCompare

这是我的代码:

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;
}

它们不是以嵌套方式运行的 for 循环,而是以顺序方式运行。输出是这样的:

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

关于为什么嵌套 for 循环没有以嵌套方式运行的任何想法?

4

1 回答 1

4

代码是正确的,除非您没有将文件分解成单词,因为您使用的是“/n”而不是“\n”。

这意味着每个数组只包含一个元素,该元素是一个包含所有单词的字符串。

于 2012-08-12T02:06:15.340 回答