当前位置:   article > 正文

QT中字符串的比较、查找、替换等操作_qt字符串替换

qt字符串替换

基本操作

  1. QString s1 = "Welcome";
  2. QString s2;
  3. s2 = s1 + "to you";
  4. QString s3 = "Hello ";
  5. s3 = s3 + "World";
  6. qDebug() << s2 << endl << s3 << endl;
  7. QString s4 = "Hello";
  8. s4.append( " World");
  9. qDebug() << s4 << endl;
  10. QString s5;
  11. s5.sprintf("%s","Welcome to my world");
  12. qDebug() << s5 << endl;
  13. QString s6;
  14. s6 = QString("I'm %1 %2").arg("is").arg("Marco");
  15. qDebug() << s6 << endl;
插入
  1. //任意位置
  2. QString s7("Marco good");
  3. s7.insert(6,"is");
  4. qDebug() << s7 << endl;
  5. //开头
  6. QString s8(" is good");
  7. s8.prepend("Marco");
  8. qDebug() << s8 << endl;

替换

  1. QString s9("Marco is bad");
  2. s9.replace("bad","good");
  3. qDebug() << s9 << endl;
移除字符串两端空白
  1. QString s10(" Marco is good ");
  2. s10 = s10.trimmed();
  3. qDebug() << s10 << endl;
移除字符串两端空白并添加一个空白符
  1. QString s11(" Marco is good ");
  2. s11 = s11.simplified();
  3. qDebug() << s11 << endl;
查询字符串内容
  1. //查询字符串开头
  2. QString s12("Welcome to you");
  3. qDebug() << s12.startsWith("Welcome",Qt::CaseSensitive) << " "
  4. << s12.startsWith("welcome",Qt::CaseInsensitive) << endl;//true
  5. //查询字符串结尾
  6. qDebug() << s12.endsWith("you",Qt::CaseSensitive) << " "
  7. << s12.endsWith("You",Qt::CaseInsensitive) << endl;//true
  8. //遍历整个字符串判断内容是否出现过
  9. qDebug() << s12.contains("to",Qt::CaseSensitive) << " "
  10. << s12.contains("To",Qt::CaseInsensitive) << endl;

比较

  1. //localeAwareCompare(const QString& ,const QString &)静态成员函数
  2. //比较两个字符串如果前者小于后者返回负整值,等于返回0,大于返回正整数
  3. if(QString::localeAwareCompare(s11,s12) < 0)
  4. qDebug() << "s11 < s12" << endl;
  5. else if(QString::localeAwareCompare(s11,s12) > 0)
  6. qDebug() << "s11 > s12" << endl;
  7. else if(QString::localeAwareCompare(s11,s12) == 0)
  8. qDebug() << "s11 == s12" << endl;
  9. //compare()//该函数可指定是否区分大小写比较,其他跟localeAwareCompare()类似
  10. if(QString::compare(s11,s12,Qt::CaseSensitive) < 0)
  11. qDebug() << "s11 < s12" << endl;
  12. else if(QString::compare(s11,s12,Qt::CaseSensitive) > 0)
  13. qDebug() << "s11 > s12" << endl;
  14. else if(QString::compare(s11,s12,Qt::CaseSensitive) == 0)
  15. qDebug() << "s11 == s12" << endl;

 

 

 

 

 

 

 

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/300075
推荐阅读
相关标签
  

闽ICP备14008679号