为什么在使用 QString::right 的字符串开头省略逗号? [英] Why a comma is omitted at the beginning of a string using QString::right?

查看:83
本文介绍了为什么在使用 QString::right 的字符串开头省略逗号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

回答 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());
}

使用这个 jsonA:

QJsonObject json {
    {"thing1", "thing1value1"},
    {"thing2", "thing2value2"},
    {"thing3", "thing3value3"}
};

和这个jsonB(注意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?

推荐答案

QString::right 函数

返回包含字符串的 n 最右边 个字符的子字符串.

Returns a substring that contains the n rightmost characters of the string.

[特别强调我的]

由于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 的字符串开头省略逗号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆