C++ Qt/C++;-如何从字符串中删除整行?

C++ Qt/C++;-如何从字符串中删除整行?,c++,qt,replace,qstring,string-split,C++,Qt,Replace,Qstring,String Split,我使用QString::remove(QString)从字符串中删除特定的行,但有一个小问题,即删除的字符串并没有真正删除,而是替换为空字符串。我想把整条线都拆了 原始字符串: ... Hi there, Alaa Joseph is here! The above line is going to be removed :P It's the magic of C++ :] ... ... Hi there, The above line is going to be removed :

我使用
QString::remove(QString)
从字符串中删除特定的行,但有一个小问题,即删除的字符串并没有真正删除,而是替换为空字符串。我想把整条线都拆了

原始字符串:

...
Hi there,
Alaa Joseph is here!
The above line is going to be removed :P

It's the magic of C++ :]
...
...
Hi there,

The above line is going to be removed :P

It's the magic of C++ :]
...
以下是我尝试过的:

test1 = originalString.replace("Alaa Joseph is here!", "");
test2 = originalString.remove("Alaa Joseph is here!");  // Same result as the previous
输出:

...
Hi there,
Alaa Joseph is here!
The above line is going to be removed :P

It's the magic of C++ :]
...
...
Hi there,

The above line is going to be removed :P

It's the magic of C++ :]
...
如上所示,它删除了文本而没有删除整行


我需要输出如下:

...
Hi there,
The above line is going to be removed :P

It's the magic of C++ :]
...
我知道我可以遍历每一行并执行以下操作:

QStringList list = test1.split("\n");

list.removeAt(0);
int n = list.length();
list.removeAt(n - 1);

QString noEmptyLines = list.join("\n");
但是我不想删除所有的空行,只删除那些我删除了内容的空行,因为这会破坏我文档的整个格式。

试试这个:

test2 = originalString.remove("Alaa Joseph is here!\n"); 
这将删除
\n
,您将获得正确的输出

如果你的任务有一些规范,你可以检查你应该做什么。例如:

if(originalString.contains("Alaa Joseph is here!\n") )
    test2 = originalString.remove("Alaa Joseph is here!\n");
else
    if(originalString.contains("Alaa Joseph is here!"))
        test2 = originalString.remove("Alaa Joseph is here!"); 

如果您确信
\n
始终在您的
字符串中,您可以避免使用此附加代码。

“它删除了文本,而没有删除整行!”否。它删除了行的文本,直到回车符,回车符是行的一部分。“\n”是字符本身。