QByteArray

QByteArray类提供了一个字节数组,通常QByteArray被用来存储了一般的字节(包括'\0')一级传统的8位以'\0'结尾的字符串。由于QByteArray封装的功能很多,使用起来比char*要方便的多,而就其内部实现来讲,它会保证所有的数据以'\0'结尾,使用隐式数据共享(copy-on-write)来减少内存消耗以及不必要的数据拷贝。

除了QByteArray,Qt中还提供了QString类来存储字符串,大部分情况下,我们都是在使用QString。QString存储了16位unicode码,很容易用来存储非ASCII或是非Lantin1的编码,另外QString在所有的QtAPI中都是通用的。有两种情况下会比较适合使用QByteArray,第一就是你要存储一般的位数据,第二种情况就是在内存资源很珍贵的情况下,例如像Qt for EmbeddedLinux
使用QByteArray很简单,使用普通的字符串即可构造,如下所示:
  1. QByteArray ba("Hello");
复制代码
上述代码中ba的size()是5,但由于其在最后要存储额外的'\0',其实际占用空间是6,这点我们要注意。像上面代码一样在使用字符串构造QByteArray时,QByteArray 执行了深拷贝(deep copy),如果出于效率考虑你不想执行深拷贝请使用QByteArray::fromRawData()。

跟C++的普通数组一样,我们可以使用[]来访问其具体下表对应的字节,对于非const的QByteArray,我们可以像下面对具体的下表进行赋值:
  1. QByteArray ba;
  2. ba.resize(5);
  3. ba[0] = 0x3c;
  4. ba[1] = 0xb8;
  5. ba[2] = 0x64;
  6. ba[3] = 0x18;
  7. ba[4] = 0xca;
复制代码
For read-only access, an alternative syntax is to use at():
对于只读操作,请使用at(),因为它可以避免深拷贝,比使用[]要快,效率要高,就像下面这样:
  1. for (int i = 0; i < ba.size(); ++i) {
  2.      if (ba.at(i) >= 'a' && ba.at(i) <= 'f')
  3.          cout << "Found character in range [a-f]" << endl;
  4. }
复制代码
如果一次取出多个字符,请使用left(), right(), 或者 mid()。
QByteArray里面可以放置的size()'\0'字节(注意这里不是最后结尾的'\0'),size()方法返回整个数组的长度,其中包括你加的那些'\0'字节,如果想求的像char*一样的长度请使用请使用qstrlen()
调用resize()方法之后,新增加的空间的值是不确定的,设置所有字节为某个值请使用fill()方法。

通过data() 或者 constData()可以获得QByteArray的真实数据的指针,获得的数据指针在调用QByteArray的non-const函数之前都是有效的

QByteArray提供了很多修改字节的方法: append(), prepend(), insert(), replace(), and remove()。如下所示

QByteArray x("and");
x.prepend("rock ");         // x == "rock and"
x.append(" roll");          // x == "rock and roll"
x.replace(5, 3, "&");       // x == "rock & roll"

The replace() and remove() functions' first two arguments are the position from which to start erasing and the number of bytes that should be erased.

When you append() data to a non-empty array, the array will be reallocated and the new data copied to it. You can avoid this behavior by calling reserve(), which preallocates a certain amount of memory. You can also call capacity() to find out how much memory QByteArray actually allocated. Data appended to an empty array is not copied.

A frequent requirement is to remove whitespace characters from a byte array ('\n', '\t', ' ', etc.). If you want to remove whitespace from both ends of a QByteArray, use trimmed(). If you want to remove whitespace from both ends and replace multiple consecutive whitespaces with a single space character within the byte array, use simplified().

If you want to find all occurrences of a particular character or substring in a QByteArray, use indexOf() or lastIndexOf(). The former searches forward starting from a given index position, the latter searches backward. Both return the index position of the character or substring if they find it; otherwise, they return -1. For example, here's a typical loop that finds all occurrences of a particular substring:

QByteArray ba("We must be <b>bold</b>, very <b>bold</b>");
int j = 0;
while ((j = ba.indexOf("<b>", j)) != -1) {
     cout << "Found <b> tag at index position " << j << endl;
     ++j;
}

If you simply want to check whether a QByteArray contains a particular character or substring, use contains(). If you want to find out how many times a particular character or substring occurs in the byte array, use count(). If you want to replace all occurrences of a particular value with another, use one of the two-parameter replace() overloads.

QByteArrays can be compared using overloaded operators such as operator<(), operator<=(), operator==(), operator>=(), and so on. The comparison is based exclusively on the numeric values of the characters and is very fast, but is not what a human would expect. QString::localeAwareCompare() is a better choice for sorting user-interface strings.

For historical reasons, QByteArray distinguishes between a null byte array and an empty byte array. A null byte array is a byte array that is initialized using QByteArray's default constructor or by passing (const char *)0 to the constructor. An empty byte array is any byte array with size 0. A null byte array is always empty, but an empty byte array isn't necessarily null:

QByteArray().isNull();          // returns true
QByteArray().isEmpty();         // returns true

QByteArray("").isNull();        // returns false
QByteArray("").isEmpty();       // returns true

QByteArray("abc").isNull();     // returns false
QByteArray("abc").isEmpty();    // returns false

All functions except isNull() treat null byte arrays the same as empty byte arrays. For example, data() returns a pointer to a '\0' character for a null byte array (not a null pointer), and QByteArray() compares equal to QByteArray(""). We recommend that you always use isEmpty() and avoid isNull().
Notes on Locale
Number-String Conversions

Functions that perform conversions between numeric data types and strings are performed in the C locale, irrespective of the user's locale settings. Use QString to perform locale-aware conversions between numbers and strings.
8-bit Character Comparisons

In QByteArray, the notion of uppercase and lowercase and of which character is greater than or less than another character is locale dependent. This affects functions that support a case insensitive option or that compare or lowercase or uppercase their arguments. Case insensitive operations and comparisons will be accurate if both strings contain only ASCII characters. (If $LC_CTYPE is set, most Unix systems do "the right thing".) Functions that this affects include contains(), indexOf(), lastIndexOf(), operator<(), operator<=(), operator>(), operator>=(), toLower() and toUpper().

This issue does not apply to QStrings since they represent characters using Unicode.

See also QString and QBitArray.

你可能感兴趣的:(C++,String,unicode,qt,QByteArray)