【发布时间】:2012-07-16 06:21:42
【问题描述】:
我知道有几种不同的方法可以在文件中查找文本,尽管我还没有找到在我正在搜索的字符串之后返回文本的方法。例如,如果我要在 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");
}
【问题讨论】:
标签: objective-c nsstring nsrange