在Qt中与字符串操作相关的类有QLatin1Char,QLatin1String,QChar,QString,QByteArray,QStringRef, QStringList,QStringMatcher,QByteArrayMatcher
(1)QLatin1Char
QLatin1Char是个结构体,存储一个8位ASCII/Latin-1编码的字符,数据的存储类型为char
1 struct QLatin1Char 2 { 3 public: 4 inline explicit QLatin1Char(char c) : ch(c) {} 5 ...... 6 private: 7 char ch; 8 };
(2)QLatin1String
QLatin1String类提供了对US-ASCII/Latin-1编码字符串常量的封装
1 class Q_CORE_EXPORT QLatin1String 2 { 3 public: 4 inline explicit QLatin1String(const char *s) : chars(s) {} 5 ...... 6 inline const char *latin1() const { return chars; } 7 ...... 8 private: 9 const char *chars; 10 };
从类声明中可以看出,QLatin1String将数据存储为const char*的数据类型
(3)QChar
1 class Q_CORE_EXPORT QChar 2 { 3 ...... 4 private: 5 ...... 6 ushort ucs; 7 };
QChar存储一个16位(2个字节)的Unicode字符,数据的存储类型为ushort(unsigned short)
(4)QString
QString是Unicode编码的字符串,存储一系列16位的QChar,每一个QChar对应一个Unicode 4.0编码的字符
1 class Q_CORE_EXPORT QString 2 { 3 ...... 4 private: 5 ...... 6 struct Data { 7 QBasicAtomicInt ref; 8 int alloc, size; 9 ushort *data; // QT5: put that after the bit field to fill alignment gap; don't use sizeof any more then 10 ushort clean : 1; 11 ushort simpletext : 1; 12 ushort righttoleft : 1; 13 ushort asciiCache : 1; 14 ushort capacity : 1; 15 ushort reserved : 11; 16 // ### Qt5: try to ensure that "array" is aligned to 16 bytes on both 32- and 64-bit 17 ushort array[1]; 18 }; 19 static Data shared_null; 20 static Data shared_empty; 21 Data *d; 22 ...... 23 };
1 QString::QString(const QChar *unicode, int size) 2 { 3 if (!unicode) { 4 d = &shared_null; 5 d->ref.ref(); 6 } else if (size <= 0) { 7 d = &shared_empty; 8 d->ref.ref(); 9 } else { 10 d = (Data*) qMalloc(sizeof(Data)+size*sizeof(QChar)); 11 Q_CHECK_PTR(d); 12 d->ref = 1; 13 d->alloc = d->size = size; 14 d->clean = d->asciiCache = d->simpletext = d->righttoleft = d->capacity = 0; 15 d->data = d->array; 16 memcpy(d->array, unicode, size * sizeof(QChar)); 17 d->array[size] = '