[英]Objective-C, get string from text file?
I know there are a few different ways to find text in file, although I haven't found a way to return the text after the string I'm searching for. 我知道有几种不同的方法可以在文件中查找文本,虽然我找不到在我搜索的字符串后返回文本的方法。 For example, if I was to search file.txt for the term foo
and wanted to return bar
, how would I do that without knowing it's bar
or the length? 例如,如果我要搜索file.txt中的术语foo
并想要返回bar
,那么如果不知道它的bar
或长度,我该怎么做呢?
Here's the code I'm using: 这是我正在使用的代码:
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");
}
You might want to use RegexKitLite and perform a regex look up: 您可能想要使用RegexKitLite并执行正则表达式查找:
NSArray * captures = [myFileString componentsMatchedByRegex:@"foo\\s+(\\w+)"];
NSString * wordAfterFoo = captures[1];
Not test though. 虽然不测试。
you could use [NSString substringFromIndex:] 你可以使用[NSString substringFromIndex:]
if (result.location == NSNotFound)
{
// foo not found. Bail.
NSLog(@"foo not found in file");
return;
}
else
{
int startingPosition = result.location + result.length;
NSString* foo = [fileContentsString substringFromIndex:startingPosition]
NSLog(@"found foo = %@",foo);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.