如何有效地从一个大的txt文件中读取字符串

How to efficiently read only strings from a big txt file

本文关键字:txt 文件 字符串 读取 一个 有效地      更新时间:2023-10-16

我有一个非常大的。txt文件(9mb)。其中,单词的存储方式如下:

да 2337093
е 1504540
не 1480296
се 1212312

.txt文件中的每一行都是一个字符串,后跟一个空格和一个数字。
我只想获取单词并将它们存储在字符串数组中。我看到一个正则表达式在这里是多余的,但没有想到另一种方法,因为我不熟悉c++中的流。

类似于下面的示例

#include <bits/stdc++.h>
using namespace std;
int main() {
    vector<string> strings;
    ifstream file("path_to_file");
    string line;
    while (getline(file, line))
        strings.push_back(line.substr(0, line.find(" ")));
    // Do whatever you want with 'strings' vector
}

您应该逐行读取文件,并且对于每行使用string的substr()方法根据空格位置解析该行,并且您可以使用find()方法查找分隔符的位置。取空格前的单词部分,忽略其余部分。