我知道有几种不同的方法可以在文件中查找文本,尽管我还没有找到在我正在搜索的字符串之后返回文本的方法。例如,如果我要在 file.txt 中搜索该术语foo
并想返回bar
,我将如何在不知道它bar
或长度的情况下执行此操作?
这是我正在使用的代码:
if (!fileContentsString) {
NSLog(@"Error reading file");
}
// Create the string to search for
NSString *search = @"foo";
// Search the file contents for the given string, put the results into an NSRange structure
NSRange result = [fileContentsString rangeOfString:search];
// -rangeOfString returns the location of the string NSRange.location or NSNotFound.
if (result.location == NSNotFound) {
// foo not found. Bail.
NSLog(@"foo not found in file");
return;
}
// Continue processing
NSLog(@"foo found in file");
}