【问题标题】:Objective-C, get string from text file?Objective-C,从文本文件中获取字符串?
【发布时间】: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


    【解决方案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);  
    }
    

    【讨论】:

    • 谢谢 - 我会试试这个。 xingzhi.sg 的例子有什么优点/缺点吗?只是好奇。
    • 我的解决方案更容易完成这项任务(尤其是如果您不熟悉正则表达式)。而且它只需要 iOS 2.0 或 OS X 10.0,所以你不需要在你的项目中携带额外的库
    • imageKey 必须是 iOS 特定的?我正在尝试为 OS X 创建这个,有没有等价的?
    • 抱歉 imageKey 是我项目中的局部变量。我编辑了我的答案,它应该是你的局部变量fileContentsString
    • 好的,我明白了。现在的问题是bar 之后的任何内容也会显示出来。例如foo bar is the string 将导致bar is the string。我如何只显示bar?
    【解决方案2】:

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

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

    虽然没有测试。

    【讨论】:

    • 我在NSString * wordAfterFoo = captures[1]; 上得到一个错误——下标需要接口NSArray 的大小,这在非脆弱ABI 中不是恒定的
    • oops... 应该是 [captures objectAtIndex:1];
    猜你喜欢
    • 2015-08-06
    • 1970-01-01
    • 2012-05-28
    • 2010-11-09
    • 2011-11-05
    • 2012-12-11
    • 2016-01-15
    • 1970-01-01
    • 2011-02-27
    相关资源
    最近更新 更多