QString的功能

一、字符串与数值之间的转换

 1.从QString类从字符串转换为数值的函数:

  int toInt (bool *ok = Q_NULLPTR, int base = 10);

  long toLong (bool *ok = Q_NULLPTR, int base = 10);

  short toShort (bool *ok = Q_NULLPTR, int base = 10);

  uint toUInt (bool *ok = Q_NULLPTR, int base = 10);

  ulong toULong (bool *ok = Q_NULLPTR, int base = 10);

  double toDouble (bool *ok = Q_NULLPTR, int base = 10);

  float toFloat (bool *ok = Q_NULLPTR, int base = 10);

2.数值转为QString类

  T total = 333;

  str = QString::number(total, 'f', 2); //可进行进制转换

  str = QString::asprintf("%.2f", total);

  str = str.setNum(total, 'f', 2);//可进行进制转换

  str = str.sprintf("%.2f", total);

二、QString常用功能

  • append() 和 prepend()
    QString str1 = "A", str2 = "B"
    QString str3 = str1;
    str1.append(str2);  //str1 = "AB"   
    str3.prepend(str2); //str3 = "BA"
  • toUpper() 和 toLower() 

    toUpper()将字符串内的字母全部转换为大写形式,toLower()将字母全部转换为小写模式。

  • count(), size(), length()

    都返回字符串的个数。

  • trimmed() 和 simplified()

    trimmed()去掉字符串首尾的空格,simplified()不仅去掉收尾的空格,中间连续的空格也用一个空格代替。

  • indexOf() 和 lastIndexOf()

    int indexOf (const QString &str, int form = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive)

   其功能是在自身字符串内查找参数字符串str出现的位置,参数form是开始查找的位置,Qt::CaseSensitivity cs参数指定是否区分大小写。

   lastIndexOf()函数则是查找某个字符串最后出现的位置。

  • contains()

    判断字符串内是否包含某个字符串,可指定是否区分大小写。

  • endsWith() 和 startsWith()

    startsWith()判断是否以某个字符串开头,endsWith()判断是否以某个字符串结束。

  • left() 和 right()

    left 表示从字符串中取左边多少个字符,right 表示从字符串中取右边多少个字符。

  • section()

    QString section (const QString &sep, int start, int end = -1, SectionFlags flags = SectionDefault) const

   其功能是从字符串中提取以sep作为分隔符,从start端到end端的字符串

QString str2, str1 = "学生姓名, 男, 1984-3-4, 汉族, 山西";
str2 = str1.section(",", 0, 0);    //str2 = "学生姓名"
str2 = str1.section(",", 1, 1);    //str2 = "男"
str2 = str1.section(",", 0, 1);    //str2 = "学生姓名, 男"
str2 = str1.section(",", 4, 4);    //str2 = "山西"

  

 Study in 《Qt5.9 C++开发指南》

猜你喜欢

转载自www.cnblogs.com/foreversdf/p/12817073.html