我正在使用QString::remove(QString)
从字符串中删除特定行,但是存在一个小问题,即删除的字符串并未真正删除,而是替换为空字符串。我想完全删除整行。
原始字符串:
...
Hi there,
Alaa Joseph is here!
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,
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");
但我不想删除所有空行,只删除其内容,因为这会破坏我的文档的整个格式。
答案 0 :(得分:1)
试试这个:
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
始终位于string
,则可以避免使用此附加代码。