【发布时间】:2022-08-12 02:24:23
【问题描述】:
问题
我正在尝试将字符串转换为 C 字符串。为此,我需要将\" 替换为\\\"。我使用以下代码来执行此操作:
QString Converter::plain2C(const QString &in) {
QString out;
// Split input in each line
QStringList list = in.split(QChar(\'\\n\'));
for (int i = 0; list.length() > i; i++) { // Go throught each line of the input
QString line = list[i]; // Thats the line
line.replace(QChar(\'\\\\\'), QLatin1String(\"\\\\\\\\\")); // replace \\ with \\\\
line.replace(QChar(\'\"\'), QLatin1String(\"\\\\\\\"\")); // replace \" with \\\"
// For printf()
if(escapePercent)
line.replace(QChar(\'%\'), QLatin1String(\"%%\"));
// If option \"Split output into multiple lines\" is active add a \" to the output
if (multiLine)
out.append(QChar(\'\"\'));
// append the line to the output
out.append(line);
// append a \"\\n\" to the output because we are at the end of a line
if (list.length() -1 > i)
out.append(QLatin1String(\"\\\\n\"));
// If option \"Split output into multiple lines\" is active add a \" and \\n to the output
if (multiLine) {
out.append(QChar(\'\"\'));
out.append(QChar(\'\\n\'));
}
}
if (!multiLine) {
out.prepend(QChar(\'\"\'));
out.append(QChar(\'\"\'));
}
return out;
}
但是,\" 仍然存在,之前没有 \\。
信息
- Qt 版本 5.15.3
- C++17
编辑
该应用程序用于输入从 Internet 复制的普通字符串,并得到一个可以复制到 C/C++ 程序中的字符串。
更多代码
void Converter::run()
{
if (_from != From::NotSupportet &&
_to != To::toInvalid) {
QString out;
// More code obove and below
else if (_from == From::Plain) {
switch (_to) {
case To::toCString:
out = plain2C(_in);
break;
// Emits the ready string which is applied direct to a QPlainTextEdit
emit htmlReady(out);
}
}
编辑 2
在代码中添加了更多 cmets
-
replace我认为返回一个新实例,而不是修改当前? -
@TZHX all overloads of
QString::replace不是 const 方法并返回QString &。所以你错了。 -
我认为我们需要查看您检查功能是否有效的代码。我在您编写的代码中看不到问题,所以问题可能出在您检查返回的字符串的位置。
-
我怀疑这部分逻辑只是混淆了:
if (multiLine)- 它添加了\"而没有 \\ 前缀。 -
@Marek R:输入在每一行中拆分并存储在一个列表中,然后我遍历每一行,如果启用了“输出到多行”选项,它会在每个行的开头和结尾添加一个
\"排。
标签: c++ qt replace c++17 qstring