【问题标题】:Unable to change integer in QString无法更改 QString 中的整数
【发布时间】:2017-05-23 14:51:08
【问题描述】:

我有一个QString strLayout,其值为"3,1,0"

我想把它改成“2,1,0”。

所以我提取了第一个字符,转换为数字并从中减去 1:

int temp = (strLayout.at(0).digitValue() - 1);

现在,我希望它写回原来的QString strLayout,如下:

strLayout[0] = temp;

问题是这不会将第一个字符替换为2

提前致谢!

【问题讨论】:

  • not able to do it 为什么?你有错误吗?这是什么?
  • 请阅读文档:doc.qt.io/qt-5/qstring.html#replace-8strLayout.replace(strLayout.split(',').at(0), QString::number(strLayout.at(0).digitValue() - 1));
  • strLayout[0] = temp;
  • 不要评论。把它放在问题中。您尝试做什么,您期望发生什么,以及发生了什么。
  • 感谢@IMAN4K 将我指向文档。我会尝试理解那里的代码。您的解决方案适用于我的代码。

标签: qt


【解决方案1】:

您的代码的问题是数字2和字符'2'之间的差异,根据ASCII编码对应50

strLayout[0] = temp; 会将数字temp (2) 重新解释为编码为2 的字符,即表示Start of Text 的特殊字符。

存在三种解决方案:

  • 将整数转回字符串:

    strLayout[0] = QString::number(temp)[0];
    
  • 不要将你的字符转换为整数:

    strLayout[0] = strLayout.at(0) - 1;
    

    这个技巧之所以有效,是因为 ASCII 字符集将数字编码为连续保持其正常顺序(数字 0-9 对应于 48-57 ASCII 值)

  • 将整数转换回字符

    strLayout[0] = temp + '0';
    

    这会将数字 0 的 ASCII 值添加到整数 temp

【讨论】:

    猜你喜欢
    • 2016-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多