Qt字符串

Qt String 类内容

字符串和数值之间的转换

QString字符串转换成数值

对于基本的数值,字符串都能进行转换

1
2
3
4
5
6
7
int toInt(bool *ok = Q_NULLPTR, int base = 10) const
long toLong(bool *ok = Q_NULLPTR, int base = 10) const
short toShort(bool *ok = Q_NULLPTR, int base = 10) const
uint toUInt(bool *ok = Q_NULLPTR, int base = 10) const
ulong toULong(bool *ok = Q_NULLPTR, int base = 10) const
double toDouble(bool *ok = Q_NULLPTR) const
float toFloat(bool *ok = Q_NULLPTR) const

当转换成功,ok置为true,否则为false,base是进制大小,默认是十进制。

数值转换成字符串

1
2
3
4
5
6
7
8
9
QString::number(int n, int base = 10);
QString::number(uint n, int base = 10);
QString::number(ulong n, int base = 10);
QString::number(qlonglong n, int base = 10);
QString::number(qulonglong n, int base = 10);
QString::number(double n, char format = 'g', int precision = 6);
QString::asprintf(const char *cformat, ...);
str.setNum(...);//与QString::number相同
str.sprintf(...);//与QString::asprintf相同

字符串常用方法

  • append()、prepend()
    append()在字符串后插,prepend()在字符串前插。

  • toUpper()、toLower()
    toUpper()小写转换成大写,toLower()转成小写。

  • count()、size()、length()
    三个都是获取字符串的长度,一个汉字算一个字节

  • trimmed()、simplified()
    trimmed()去掉整个字符串前后的空格,simplified()去掉前后、中间的空格。

  • indexOf()&lastIndexOf()
    indexOf(str,from)是在自身字符串内查找str,从from开始查找,返回最先出现的位置。
    lastIndexOf(str, from)返回最后出现的位置。

  • isNull()&isEmpty()
    isNull()和isEmpty()都是判断字符串为空。如果字符串中只有”\0”,isNull返回false,isEmpty返回true,未赋值的字符串isNull才返回true。

  • contains()
    判断父字符串是否包含子字符串,返回true&false。

  • endsWith()&startsWith()
    startsWith(str)判断是否以str开始,endsWith(str)判断是否以str结束。

  • left()&right()
    left(num)从字符串左边取num个字符,right(num)从字符串右边取num个字符。

  • section()
    section(sep, start, end)从字符串提取以sep为分隔符,从start端到end端。例如:

    1
    2
    3
    QString s1 = "shanghai, beijing, guangzhou, Hongkong", s2;
    s2 = s1.section(",", 0, 0)//s2 = "shanghai"
    s2 = s1.section(",", 1, 3)//s2 = "beijing, guangzhou, Hongkong"
0%