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

How to efficiently read only strings from a big txt file

我有一个非常大的 .txt 文件 (9 MB)。其中的单词是这样存储的:

да 2337093
е 1504540
не 1480296
се 1212312

.txt 文件中的每一行都包含一个字符串,后跟一个 space 和一个数字。
我只想获取单词并将它们存储在字符串数组中。我看到正则表达式在这里会有点矫枉过正,但由于我不熟悉 C++ 中的流,所以没有想到另一种方法。

你应该逐行读取文件,并且对于每一行使用字符串的substr()方法根据space位置解析一行,你可以使用find()方法找到分隔符的位置。取 space 之前的单词部分并忽略其余部分。

您可以查看 here 示例。

类似于下面的示例

#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
}