我有以下文本文件结构(该文本文件相当大,约有10万行):
A|a1|111|111|111
B|111|111|111|111
A|a2|222|222|222
B|222|222|222|222
B|222|222|222|222
A|a3|333|333|333
B|333|333|333|333
...
我需要提取与给定关键字相关的文本。例如,如果我的关键字是A|a2,我需要将以下内容保存为字符串:
A|a2|222|222|222
B|222|222|222|222
B|222|222|222|222
在我的C++和Objective C项目中,我使用了以下方式的C++ getline函数:
std::ifstream ifs(dataPathStr.c_str());
NSString* searchKey = @"A|a2";
std::string search_string ([searchKey cStringUsingEncoding:NSUTF8StringEncoding]);
// read and discard lines from the stream till we get to a line starting with the search_string
std::string line;
while( getline( ifs, line ) && line.find(search_string) != 0 );
// check if we have found such a line, if not report an error
if( line.find(search_string) != 0 )
{
data = DATA_DEFAULT ;
}
else{
// we need to form a string that would include the whole set of data based on the selection
dataStr = line + '\n' ; // result initially contains the first line
// now keep reading line by line till we get an empty line or eof
while(getline( ifs, line ) && !line.empty() )
{
dataStr += line + '\n'; // append this line to the result
}
data = [NSString stringWithUTF8String:navDataStr.c_str()];
}
由于我正在使用Swift进行项目开发,我试图摆脱getline并使用一些"Cocoaish"的东西来替换它。但是我找不到一个好的Swift解决方案来解决上述问题。如果您有想法,我会非常感激。谢谢!
nextLine()
调用将作为字符串返回文件中的一行。默认分隔符是换行符(\n
)。分隔符不包含在返回的字符串中。 - Martin Rlet bundle = NSBundle.mainBundle()
let pathNav = bundle.pathForResource("data_apt", ofType: "txt")
if let aStreamReader = StreamReader(path: pathNav!) { while let line = aStreamReader.nextLine() { println(line) }
仍然读取整个数据库,而不是按分隔符\n读取行。 - Igor Tupitsyn