我正在使用 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");
但我不想删除所有空行,只删除那些我删除了内容的行,因为这会破坏我文档的整个格式。
最佳答案
试试这个:
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
中,则可以避免此附加代码。
关于c++ - Qt/C++ - 如何从字符串中删除整行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26615245/