Objective-C,从文本文件中获取字符串?

时间:2012-07-16 06:21:42

标签: objective-c nsstring nsrange

我知道有几种不同的方法可以在文件中查找文本,虽然我找不到在我搜索的字符串后返回文本的方法。例如,如果我要搜索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");    
}

2 个答案:

答案 0 :(得分:1)

您可能希望使用RegexKitLite并执行正则表达式查找:

NSArray * captures = [myFileString componentsMatchedByRegex:@"foo\\s+(\\w+)"];
NSString * wordAfterFoo = captures[1];

虽然没有测试。

答案 1 :(得分:1)

您可以使用[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);  
}