问题描述
回答 QString 替换引号之外的字符 我偶然发现了一个奇怪的行为.
Answering QString replace characters outside of quotes I have stumbled upon a strange behavior.
执行此代码:
foreach (const QString &key, json.keys()) {
const QJsonValue &value(json.value(key));
qDebug() << key << value.toString().right(key.length());
}
使用这个 json
,A:
QJsonObject json {
{"thing1", "thing1value1"},
{"thing2", "thing2value2"},
{"thing3", "thing3value3"}
};
和这个json
,B(注意thing2
后面的逗号):
and with this json
, B (notice the comma after thing2
):
QJsonObject json {
{"thing1", "thing1value1"},
{"thing2", "thing2,value2"},
{"thing3", "thing3value3"}
};
在这两种情况下都会产生:
in both cases produces:
"thing1" "value1"
"thing2" "value2"
"thing3" "value3"
不应该:
"thing1" "value1"
"thing2" ",value2"
"thing3" "value3"
在第二种情况下,B?
推荐答案
返回包含字符串的 n
最右边 个字符的子字符串.
由于key字符串的长度是6
,那么6
最右边的字符将被返回,给你"value2"
,没有逗号.
Since the length of the key string is 6
, then the 6
rightmost characters will be returned, giving you "value2"
without the comma.
如果你想得到没有前导键的字符串,你可以使用 mid
代替:
If you want to get the string without the leading key you could use mid
instead:
value.toString().mid(key.length())
对于您的用例,我宁愿建议 midRef代码>
,因为实际上不需要创建子字符串的副本.
For your use-case I would rather suggest midRef
, since there's no need to actually create a copy of the sub-string.
这篇关于为什么在使用 QString::right 的字符串开头省略逗号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!