数组比较和不寻常的结果

时间:2011-12-13 05:18:54

标签: objective-c nsarray

这里的代码我有一个句子,我将它转换为数组,然后我有另一个数组,这是一个停止列表,我想通过停止列表过滤我的句子,意味着最后一句不应该包含停止列表元素!< / p>

它似乎很容易,我为了让它起作用而自杀了,但它从未奏效!天啊!

你可以告诉我这是什么问题吗?

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];



    NSString *sentence=[NSString stringWithString:@"i want to filter this sentence by stoplist array for my program"];


    NSArray *stopList=[[NSArray alloc]initWithObjects:@"an”,@“and”,@“by”,@“for”,@“from”,@“of”,@“the”,@“to”,@“with",nil];

    NSArray *query = [sentence componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

    NSMutableArray *finalsentence=[NSMutableArray array];


    for (NSString *word in query) { // for each word in the query...

        if (![stopList containsObject:word]) { 
            // ... if the stopList does not contain the word...

            [finalsentence addObject:word]; // ...add it to the final sentence
        }
    }
    NSLog(@"%@",finalsentence);


    [pool drain];
    return 0;
}

1 个答案:

答案 0 :(得分:0)

嗯,有一个问题是[finalsentence addObject:q]中的“q”是什么?您的代码中没有定义“q”。

另一个问题是你似乎从你给出的描述中反向进行了测试。您的描述表明您希望将每个单词添加到'finalsentence',如果该单词在您的stopList中为NOT。但是在代码中,您要检查[stopList containsObject:[query objectAtIndex:i]]是否为YES。我想你应该在那里检查NO。

此外,使用快速枚举语法可以更清楚地表达for循环:

for (NSString *word in query) { // for each word in the query...

        if (![stopList containsObject:word]) { 
            // ... if the stopList does not contain the word...

            [finalsentence addObject:word]; // ...add it to the final sentence
        }
    }

我希望有所帮助。

修改

以下是复制,粘贴,运行更新代码后的输出。好像做你想说的,不是吗?

2011-12-13 03:36:55.544 Some6[8082:707] (
i,
want,
filter,
this,
sentence,
stoplist,
array,
my,
program
)