2012-05-15 27 views
-2

我在項目中包含了一個.txt文件,我必須在搜索欄中輸入關鍵字才能從該文件中找到關鍵字。幫助我找到一段代碼,用於搜索文件中存在的關鍵字。如何搜索已包含在xcode項目中的.txt文件中的單詞

+1

你只是想驗證在搜索欄中輸入的關鍵字是否存在於.txt文件中,或者在輸入搜索文字後要達到什麼目的? – Jailbroken

+0

文件有多大?它是否有設置的格式?你能改變格式嗎?你在做部分比賽嗎? @VishalVaja – Wain

回答

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只解析該文件的數據塊

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; 

} 

你可以去這裏瞭解更多details

相關問題