从字符串中删除空行

removing empty lines from a string c++

本文关键字:删除 字符串      更新时间:2023-10-16

我试图删除创建的空行,当我从一个文件中的列表中删除一个人,所以我的文件打开时看起来好多了。这是代码,我必须删除这一行。

std::ifstream ifs("alpha.dat");

  std::ofstream tem("temporary.text");
std::string str((std::istreambuf_iterator<char>(ifs)),
std::istreambuf_iterator<char>());
str.erase(std::remove(str.begin(), str.end(), 'n'), str.end());

cout << str;
tem << str;
tem.close();    
ifs.close();

我的文件内容如下:

maria hernandez 1000 h3777 +1000 19:15:19    
rachel dominguez 100000 X8793 +100000 19:15:20                                                  
carlos yatch 20 g6386 +20 19:15:20 
Empty line
carlos Domingues 20 g3336 +20 19:15:20                                                                                                                
Empty Line

但是我得到的是当前文件:

maria hernandez 1000 h3777 +1000 19:15:19 rachel dominguez 100000 X8793 +100000 19:15:20 carlos yatch 20 g6386 +20 19:15:20 

您不应该删除所有的n。它们不代表空行,而是换行符的开始。当你连续得到一个以上的n时,你得到一个空行。

对于删除这些连续的n字符,我建议替换:

str.erase(std::remove(str.begin(), str.end(), 'n'), str.end());

,像这样:

str.erase(std::unique(str.begin(), str.end(),
                      [] (char a, char b) {return a == 'n' && b == 'n';}),
          str.end());

此处为工作示例。

std::unique删除相等的连续元素。但是因为我们只想删除换行符,所以我们传递一个lambda作为谓词。最后,我们只需要删除重复的n,它被移动到容器的末尾。

要删除空行,您需要确保通过将它们全部转换为n来删除冗余的r,同时确保不会意外添加行({'r', 'n'}),然后这是删除重复项的简单任务。

查找出现两次的回车,并删除其中一个。

size_t pos;
while ((pos= str.find("nn", 0)) != std::string::npos)
{
    str.erase(pos, 1);
}

在这里运行

/* Processing of text lines the method length()
 The search for the longest line of the text.
 Removing of the particular line of text.
The first step.
 Write a function to find the empty line of the text file:*/
//------------------------------------------------------------
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int Find();
void Remove( int k);
//------------------------------------------------------------
int main()
{
 cout << "blank line no "<<"is:   "<<Find()<<endl;
 Remove(Find());
 return 0;
}
//------------------------------------------------------------
int Find()
{
 int nr = 0; string ilg = "";
 int n = 0; string eil;
 ifstream fd("Data.txt");
 while (!fd.eof()) {
 getline(fd, eil);
 for(int i=0;i<n;i++)
 {  
 if (eil.length() == 0) {
     nr = n; ilg = eil;}
 }
 n++;
 }
  fd.close();
 return nr;
}
//---------------------
/*The second step. Write a function to remove the given line:*/
//------------------------------------------------------------
void Remove( int k)
{
 string eil;
 ofstream fr("Result.txt");
 ifstream fd("Data.txt");
 // The lines are copied till the removed
 for (int i = 0; i < k; i++) {
 getline(fd, eil);
 fr << eil << endl;
 }
 // The line, which has to be removed, is not copied
 getline(fd, eil);
 // The remaining lines are copied
 while (!fd.eof()) {
 getline(fd, eil);
 fr << eil << endl;
 }
 fd.close();
 fr.close();
}
//---