【问题标题】:How to remove the first two characters of a QString如何删除QString的前两个字符
【发布时间】:2017-03-07 13:31:27
【问题描述】:

我将如何删除 QString 的前两个字符,或者如果我必须把它放在 StackOverflows 外行的术语中:

QString str = "##Name" //output: ##Name

output: Name

到目前为止,我已经使用了这么一小段代码:

if(str.contains("##"))
{
    str.replace("##","");
}

..但它不起作用,因为我需要在其他一些字符串中包含 "##" ,但不是在开头。

前两个字符也可能是 "%$""#@",这主要是我需要删除前两个字符的原因.

有什么想法吗?

【问题讨论】:

  • str = str.right(str.size()-2) ?
  • str.remove(0,2) ?我从来没有用过 Qt,但是关于 QString 的文档看起来……非常完整。
  • Timbo 做对了!

标签: c++ qt replace qstring


【解决方案1】:

这是删除前两个字符的语法。

str.remove(0, 2); 

【讨论】:

    【解决方案2】:

    您可以为此使用QString::mid 函数:

    QString trimmed = str.mid(2);
    

    但是,如果您想就地修改字符串,最好按照其他人的建议使用QString::remove

    【讨论】:

      【解决方案3】:

      您可以使用remove(const QRegExp &rx)

      删除字符串中所有出现的正则表达式 rx,并返回对该字符串的引用。例如:

      QString str = "##Name" //output: ##Name
          str.remove(QRegExp("[#]."));
          //strr == "Name"
      

      【讨论】:

      • 这不是问题的最佳答案,但它解决了我的问题:我想删除给定字符的所有出现。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-13
      • 2020-01-22
      • 2012-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-30
      相关资源
      最近更新 更多