当前位置: 首页 > 知识库问答 >
问题:

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

聂鹏云
2023-03-14

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

...

我需要提取一段与给定键相关的文本。例如,如果我的密钥是|a2,我需要将以下内容保存为字符串:

A|a2|222|222|222
B|222|222|222|222
B|222|222|222|222

对于我的 C 和目标 C 项目,我按如下方式使用了 C 获取线函数:

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,用“可可式”的东西取而代之。但是我找不到一个好的 Swift 解决方案来解决上述问题。如果您有想法,我将不胜感激。谢谢!

共有1个答案

范鸿
2023-03-14

使用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")
}
 类似资料:
  • 问题内容: 我刚刚开始学习Swift。我有要从文本文件读取的代码,应用程序显示了整个文本文件的内容。如何显示一行一行并多次调用该行? 包含以下内容: 以下是目前的情况。 如果还有另一种方法,请告诉我。将不胜感激。 问题答案: 斯威夫特3.0 该变量应该是数据的每一行。 使用的代码来自: 在用Obj-C编写的iOSSDK中逐行读取文件并使用NSString 查看旧版Swift的编辑历史记录。

  • 我刚刚开始学习 Swift。我已经从文本文件中读取了我的代码,并且应用程序显示整个文本文件的内容。如何逐行显示并多次调用该行? 包含以下内容: 以下是目前的… 如果有别的方法,请告诉我。非常感谢。

  • 问题内容: 我正在尝试读取中给定的文件并将其加载到数组中,其中各项之间用换行符分隔。 到目前为止,这是我做的方法: 我对此不太满意,原因有两个。第一,我正在处理大小从几千字节到数百MB不等的文件。可以想象,使用如此大的字符串是缓慢且笨拙的。其次,这会在执行时冻结UI,这同样是不好的。 我已经考虑过在单独的线程中运行此代码,但是我一直在遇到麻烦,此外,它仍然不能解决处理巨大字符串的问题。 我想做的事

  • 我正在尝试读取

  • 问题内容: 我尝试了几种方法来获取文件大小,但始终为零。 我在日志中: 问题答案: 使用而不是 +调用attr上的.fileSize()。 在Swift 2.0中,我们使用do try catch模式,如下所示: 在Swift 3.x / 4.0中:

  • 如图所示,我有代码在屏幕上绘制文本。textalign函数仅支持水平对齐。现在,我要添加对垂直对齐的支持。有人能帮我一下吗? 代码