ファイル内のテキストを検索する方法がいくつかあることは知っていますが、検索している文字列の後にテキストを返す方法は見つかりませんでした。たとえば、 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");
}