【发布时间】:2021-12-01 04:21:44
【问题描述】:
我正在尝试从文本文件中删除一个字符串。为此,我想将文件读入一个向量,然后我想搜索这个字符串的位置,所以我可以使用 vector::erase 来删除它。从向量中删除字符串后,我可以将向量写入新文件。
到目前为止,我已经完成了所有这些,但要找到字符串的位置。我使用 的 std::find 找到了各种解决方案,但这些答案试图检查这个字符串是否存在,而不是它的位置。
这是一个如何设置文本文件的示例。有一个字符串,后跟一个整数,后跟 .txt,不带空格。每个字符串都在换行符上。
file123.txt
Bob56.txt'
Foo8854.txt
在这种情况下,向量将是“file123.txt”、“bob56.txt”、“Foo8854.txt”。
这是我已经编写的代码:
std::vector<std::string> FileInVector;
std::string str;
int StringPosition;
std::fstream FileNames;
FileNames.open("FileName Permanent Storage.txt");
while (std::getline(FileNames, str)) {
if(str.size() > 0) {
FileInVector.push_back(str); // Reads file, and this puts values into the vector
}
}
//This is where it would find the position of the string: "bob56.txt" as an example
FileInVector.erase(StringPosition); // Removes the string from the vector
remove("FileName Permanent Storage.txt"); // Deletes old file
std::ofstream outFile("FileName Permanent Storage.txt"); // Creates new file
for (const auto &e : FileInVector) outFile << e << "\n"; // Writes vector without string into the new file
【问题讨论】:
-
这能回答你的问题吗? How to find substring from string?
标签: c++ file vector find erase