我有一个文本文件,其中包含许多行,如下所示:
%% reason of the selling ?
%% they piggy-back on cingular 's service .
zone[-3] %% also , their t-zones ."
customer service[-2] %% since i received the phone.
%% 24 hours ?"
screen[-2] %% i must have heard this about a dozen times over the span"
我想删除以%%开头的所有行,并且还有一些行在中间包含%%,所以删除%%直到该行的末尾。我想要这样的最终结果
zone[-3]
customer service[-2]
screen[-2]
答案 0 :(得分:1)
逐行读取临时字符串。检查前两个字符是否不等于"%%"
并将该字符串插入另一个文件中:
#include <iostream>
#include <fstream>
#include <string>
int main(){
std::ifstream ifs("input.txt");
std::ofstream ofs("output.txt");
std::string tempstr;
while (std::getline(ifs, tempstr)){
if (tempstr.substr(0, 2) != "%%"){
ofs << tempstr << std::endl;
}
}
}
如果您想在任何位置跳过"%%"
行,请将上述if
语句修改为:
if (tempstr.find("%%") == std::string::npos)
答案 1 :(得分:0)
您没有'删除'行,但是您创建了没有这些行的副本。
对于小文件,您可以在内存中执行此操作。但是,对于大文件,您可以创建新文件,删除旧文件,并重命名新文件以匹配旧文件。
{{1}}
对于删除/重命名部分,请查看How to change a text file's name in C++
答案 2 :(得分:0)
您要覆盖旧文件,还是只想获取过滤后的数据? 在过滤的情况下,我不会使用专门的解决方案,只是常见的拆分函数第一个结果。
#include <string>
//surely you have your own splitting function, this is just an example
std::vector<std::string> stringSplit(std::string s, std::string delim, int start/*=0*/)
{
std::vector<std::string> result;
std::string s1 = s + delim; //to find at least one
auto delimPos = s1.find(delim, start),
delimLen = delim.length(),
pMax = s1.length(), tokenLen = delimPos - start,
startPos = delimPos - tokenLen;
while (((int)delimPos > -1) && (delimPos < pMax) )
{
tokenLen = delimPos - startPos;
result.push_back(s1.substr(startPos, tokenLen));
startPos = delimPos + delimLen;
delimPos = s1.find(delim, startPos);
}
return(result);
}
std::vector<std::string> lines = {
"%% reason of the selling ?",
"zone[-3] %% also , their t-zones .",
"customer service[-2] ## since i received the phone.",
"customer service[-2] %% since i received the phone.",
"%% 24 hours ?\"",
"screen[-2] %% i must have heard this about a dozen times over the span\"" };
std::string result;
for (auto line : lines)
{
result = (stringSplit(line, "%%"))[0];
if (result != "")
std::cout << result << std::endl;
}
输出:
zone[-3]
customer service[-2] ## since i received the phone.
customer service[-2]
screen[-2]