Objective-C,从文本文件中获取字符串?
我知道有几种不同的方法可以在文件中查找文本,尽管我还没有找到一种在搜索字符串后返回文本的方法。例如,如果我要在file.txt中搜索术语Objective-C,从文本文件中获取字符串?,objective-c,nsstring,nsrange,Objective C,Nsstring,Nsrange,我知道有几种不同的方法可以在文件中查找文本,尽管我还没有找到一种在搜索字符串后返回文本的方法。例如,如果我要在file.txt中搜索术语foo,并希望返回bar,我如何在不知道它的bar或长度的情况下执行该操作 以下是我使用的代码: if (!fileContentsString) { NSLog(@"Error reading file"); } // Create the string to search for NSString *search = @"foo"; // Sea
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");
}
您可能希望使用并执行正则表达式查找:
NSArray * captures = [myFileString componentsMatchedByRegex:@"foo\\s+(\\w+)"];
NSString * wordAfterFoo = captures[1];
但不是测试。您可以使用
谢谢,我来试试。兴志的例子有什么优点/缺点吗?只是好奇而已。我的解决方案对于这个任务更容易(特别是如果你不熟悉regex的话)。它只需要iOS 2.0或OS X 10.0,因此您不需要在项目中附带额外的库
imageKey
必须是特定于iOS的吗?;我正在尝试为OSX创建这个,有没有一个等效的呢?对不起,imageKey
是我项目中的一个局部变量。我编辑了我的答案,应该是你的局部变量fileContentsString
好的,我明白了。现在的问题是,bar
之后的任何内容也会显示出来。例如,foo-bar是字符串
将导致bar是字符串
。如何仅显示条
?我在NSString*wordAfterFoo=captures[1]上得到一个错误代码>--下标要求接口大小NSArray
,这在非脆弱ABIOPS中不是常量。。。应为[捕获对象索引:1];
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);
}