从Swift中的大文本文件中读取行直到新行为空:Swift方式

时间:2014-11-10 03:45:46

标签: swift readline getline

我有以下文本文件结构(文本文件很大,大约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

...

我需要提取与给定密钥相关的一段文本。例如,如果我的密钥是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并将其替换为#34; Cocoaish"。但我找不到一个好的Swift解决方案来解决上述问题。如果你有一个想法,我会非常感激。谢谢!

1 个答案:

答案 0 :(得分:10)

使用Read a file/URL line-by-line in Swift中的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")
}