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

标签 c++ qt replace qstring 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++ :]
...

这是我尝试过的:

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/

相关文章:

javascript - 查找特定位置的数字

c++ - 重载加法运算符时代码重复

C++ 字符数组参数在 x86 编译时包含奇怪的字符

qt - 甚至是 SplitView 中空间的初始分配

macos - 命名空间 'nullptr_t' 中没有名为 'std' 的类型

python - 如何替换 pandas DataFrame 中多个分类中的值

javascript - 替换中的回调函数(循环内)

c++ - 分配第一个非零值 (c++)

c++ - 接收所有使用 C 套接字发送的数据

java - 如何让 android 使用我的 QtActivity 子类而不是原来的 QtActivity?