Igo*_*syn 7 readline getline swift
我有以下文本文件结构(文本文件很大,大约100,000行):
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
...
Run Code Online (Sandbox Code Playgroud)
我需要提取一段与给定键相关的文本.例如,如果我的密钥是A | a2,我需要将以下内容保存为字符串:
A|a2|222|222|222
B|222|222|222|222
B|222|222|222|222
Run Code Online (Sandbox Code Playgroud)
对于我的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()];
}
Run Code Online (Sandbox Code Playgroud)
当我在Swift中做一个项目时,我试图摆脱getline并用"Cocoaish"替换它.但我找不到一个好的Swift解决方案来解决上述问题.如果你有一个想法,我会非常感激.谢谢!
Mar*_*n R 10
使用Swift中的逐行读取文件/ URL的StreamReader类,你可以像这样使用Swift:
let searchKey = "A|a2"
let bundle = NSBundle.mainBundle()
let pathNav = bundle.pathForResource("data_apt", ofType: "txt")
if let aStreamReader = StreamReader(path: pathNav!) {
var dataStr = ""
while let line = aStreamReader.nextLine() {
if line.rangeOfString(searchKey, options: nil, range: nil, locale: nil) != nil {
dataStr = line + "\n"
break
}
}
if dataStr == "" {
dataStr = "DATA_DEFAULT"
} else {
while let line = aStreamReader.nextLine() {
if countElements(line) == 0 {
break
}
dataStr += line + "\n"
}
}
aStreamReader.close()
println(dataStr)
} else {
println("cannot open file")
}
Run Code Online (Sandbox Code Playgroud)