-2

我在我的项目中包含了一个 .txt 文件,我必须通过在搜索栏中输入关键字来从该文件中找到一个关键字。帮助我使用一段代码来搜索文件中存在的关键字。

4

2 回答 2

3

试试看

//Get the contents of the file
NSString *contentString = [NSString stringWithContentOfFile:<i>path/to/your/file.txt</i> encoding:<i>textEncoding<i> error:<i>&error</i>];

if (!error) {
    NSRange range = [contentString rangeOfString:<i>yourKeyword</i>];

    if (theRange.location != NSNotFound)
       //do whatever you want
}

注意:只要您的文本文件不是“太大”,这将起作用。如果您必须处理更大的文件,请查看 NSInputStream 以仅解析文件块

于 2012-05-15T06:49:32.020 回答
0

尝试这个:

-(void)searchWord:(NSString *)wordToBeSearched{
NSString* path = [[NSBundle mainBundle] pathForResource:@"wordFile"
                                             ofType:@"txt"];

NSString* content = [NSString stringWithContentsOfFile:path
                                          encoding:NSUTF8StringEncoding
                                             error:NULL];

NSString *delimiter = @"\n";
NSArray *items = [content componentsSeparatedByString:delimiter];
NSString *character = @" ";
BOOL isContain = NO;
for (NSString *wordToBeSearched in items) {
isContain = ([string rangeOfString:wordToBeSearched].location != NSNotFound);
}
return isContain; 

}

你可以去这里了解更多详情

于 2013-09-05T10:39:04.320 回答