Qt入门-字符串类QString
原地址:http://blog.csdn.net/xgbing/article/details/7770854
QString是Unicode字符的集合,它是Qt API中使用的字符串类。
QString的成员是QChar,QChar是一个16位Unicode字符类。大多数编译器把它看作是一个unsigned short。
QString和C标准中的字符串不同,它不以'\0'结尾,相反,QString可以嵌入'\0'/字符。
(1)QString初始化。
- QString str("Hello");
- QString str = "Hello";
- static const QChar data[4] = { 0x0055, 0x006e, 0x10e3, 0x03a3 };
- QString str(data, 4);
- QString str;
- str.resize(4);
- str[0] = QChar('U');
- str[1] = QChar('n');
- str[2] = QChar(0x10e3);
- str[3] = QChar(0x03a3);
- QString str;
- str.sprintf("%s %.3f", "float", 3.1415926);
- //str结果是"float 3.14"
- QString str;
- str.setNum(10); //str = "10"
- str.setNum(10, 16); //str = "a"
- str.setNum(10.12345); //str = "10.12345"
- QString i; // current file's number
- QString total; // number of files to process
- QString fileName; // current file's name
- QString status = QString("Processing file %1 of %2: %3")
- .arg(i).arg(total).arg(fileName);
(2)字符串转换
- long toLong ( bool * ok = 0, int base = 10 ) const
- qlonglong toLongLong ( bool * ok = 0, int base = 10 ) const
- short toShort ( bool * ok = 0, int base = 10 ) const
- double toDouble ( bool * ok = 0 ) const
- float toFloat ( bool * ok = 0 ) const
- uint toUInt ( bool * ok = 0, int base = 10 ) const
- ulong toULong ( bool * ok = 0, int base = 10 ) const
- qulonglong toULongLong ( bool * ok = 0, int base = 10 ) const
- ushort toUShort ( bool * ok = 0, int base = 10 ) const
参数ok结果说明转换是否成功。
示例:
- QString str;
- bool ok;
- double d = str.toDouble(&ok);
- if(ok)
- {
- cout << str << endl;
- } else
- {
- cout << "error." << endl;
- }
(3)字符串比较
- int compare ( const QString & other ) const
- int compare ( const QString & other, Qt::CaseSensitivity cs ) const
- int compare ( const QLatin1String & other, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
- int compare ( const QStringRef & ref, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
- QString().isNull(); // returns true
- QString().isEmpty(); // returns true
- QString("").isNull(); // returns false
- QString("").isEmpty(); // returns true
- QString("abc").isNull(); // returns false
- QString("abc").isEmpty(); // returns false
(4)字符串处理
QStringleft ( int n ) const //取左边的n个字符。
QStringright ( int n ) const //取右边的n个字符。
replace()函数提供方法替换字符串。
remove()函数从字符串中移除字符。
split()函数拆分字符串。
mid()取子串。