![]() |
Home · All Namespaces · All Classes · Main Classes · Grouped Classes · Modules · Functions |
The QString class provides a Unicode character string. More...
#include <QString>
Inherited by QConstString, QDBusObjectPath, and QDBusSignature.
Note: All the functions in this class are reentrant, except ascii(), latin1(), utf8(), and local8Bit().
The QString class provides a Unicode character string.
QString stores a string of 16-bit QChars, where each QChar corresponds one Unicode 4.0 character. (Unicode characters with code values above 65535 are stored using surrogate pairs, i.e., two consecutive QChars.)
Unicode is an international standard that supports most of the writing systems in use today. It is a superset of ASCII and Latin-1 (ISO 8859-1), and all the ASCII/Latin-1 characters are available at the same code positions.
Behind the scenes, QString uses implicit sharing (copy-on-write) to reduce memory usage and to avoid the needless copying of data. This also helps reduce the inherent overhead of storing 16-bit characters instead of 8-bit characters.
In addition to QString, Qt also provides the QByteArray class to store raw bytes and traditional 8-bit '\0'-terminated strings. For most purposes, QString is the class you want to use. It is used throughout the Qt API, and the Unicode support ensures that your applications will be easy to translate if you want to expand your application's market at some point. The two main cases where QByteArray is appropriate are when you need to store raw binary data, and when memory conservation is critical (e.g., with Qt for Embedded Linux).
One way to initialize a QString is simply to pass a const char * to its constructor. For example, the following code creates a QString of size 5 containing the data "Hello":
QString str = "Hello";
QString converts the const char * data into Unicode using the fromAscii() function. By default, fromAscii() treats character above 128 as Latin-1 characters, but this can be changed by calling QTextCodec::setCodecForCStrings().
In all of the QString functions that take const char * parameters, the const char * is interpreted as a classic C-style '\0'-terminated string. It is legal for the const char * parameter to be 0.
You can also provide string data as an array of QChars:
static const QChar data[4] = { 0x0055, 0x006e, 0x10e3, 0x03a3 };
QString str(data, 4);
QString makes a deep copy of the QChar data, so you can modify it later without experiencing side effects. (If for performance reasons you don't want to take a deep copy of the character data, use QString::fromRawData() instead.)
Another approach is to set the size of the string using resize() and to initialize the data character per character. QString uses 0-based indexes, just like C++ arrays. To access the character at a particular index position, you can use operator[](). On non-const strings, operator[]() returns a reference to a character that can be used on the left side of an assignment. For example:
QString str;
str.resize(4);
str[0] = QChar('U');
str[1] = QChar('n');
str[2] = QChar(0x10e3);
str[3] = QChar(0x03a3);
For read-only access, an alternative syntax is to use the at() function:
QString str;
for (int i = 0; i < str.size(); ++i) {
if (str.at(i) >= QChar('a') && str.at(i) <= QChar('f'))
qDebug() << "Found character in range [a-f]";
}
The at() function can be faster than operator[](), because it never causes a deep copy to occur. Alternatively, use the left(), right(), or mid() functions to extract several characters at a time.
A QString can embed '\0' characters (QChar::null). The size() function always returns the size of the whole string, including embedded '\0' characters.
After a call to the resize() function, newly allocated characters have undefined values. To set all the characters in the string to a particular value, use the fill() function.
QString provides dozens of overloads designed to simplify string usage. For example, if you want to compare a QString with a string literal, you can write code like this and it will work as expected:
QString str;
if (str == "auto" || str == "extern"
|| str == "static" || str == "register") {
// ...
}
You can also pass string literals to functions that take QStrings as arguments, invoking the QString(const char *) constructor. Similarly, you can pass a QString to a function that takes a const char * argument using the qPrintable() macro which returns the given QString as a const char *. This is equivalent to calling <QString>.toLocal8Bit().constData().
QString provides the following basic functions for modifying the character data: append(), prepend(), insert(), replace(), and remove(). For example:
QString str = "and";
str.prepend("rock "); // str == "rock and"
str.append(" roll"); // str == "rock and roll"
str.replace(5, 3, "&"); // str == "rock & roll"
If you are building a QString gradually and know in advance approximately how many characters the QString will contain, you can call reserve(), asking QString to preallocate a certain amount of memory. You can also call capacity() to find out how much memory QString actually allocated.
The replace() and remove() functions' first two arguments are the position from which to start erasing and the number of characters that should be erased. If you want to replace all occurrences of a particular substring with another, use one of the two-parameter replace() overloads.
A frequent requirement is to remove whitespace characters from a string ('\n', '\t', ' ', etc.). If you want to remove whitespace from both ends of a QString, use the trimmed() function. If you want to remove whitespace from both ends and replace multiple consecutive whitespaces with a single space character within the string, use simplified().
If you want to find all occurrences of a particular character or substring in a QString, use the indexOf() or lastIndexOf() functions. 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:
QString str = "We must be <b>bold</b>, very <b>bold</b>";
int j = 0;
while ((j = str.indexOf("<b>", j)) != -1) {
qDebug() << "Found <b> tag at index position" << j;
++j;
}
QString provides many functions for converting numbers into strings and strings into numbers. See the arg() functions, the setNum() functions, the number() static functions, and the toInt(), toDouble(), and similar functions.
To get an upper- or lowercase version of a string use toUpper() or toLower().
Lists of strings are handled by the QStringList class. You can split a string into a list of strings using the split() function, and join a list of strings into a single string with an optional separator using QStringList::join(). You can obtain a list of strings from a string list that contain a particular substring or that match a particular QRegExp using the QStringList::find() function. :
If you want to see if a QString starts or ends with a particular substring use startsWith() or endsWith(). If you simply want to check whether a QString contains a particular character or substring, use the contains() function. If you want to find out how many times a particular character or substring occurs in the string, use count().
QStrings can be compared using overloaded operators such as operator<(), operator<=(), operator==(), operator>=(), and so on. Note that the comparison is based exclusively on the numeric Unicode values of the characters. It is very fast, but is not what a human would expect; the QString::localeAwareCompare() function is a better choice for sorting user-interface strings.
To obtain a pointer to the actual character data, call data() or constData(). These functions return a pointer to the beginning of the QChar data. The pointer is guaranteed to remain valid until a non-const function is called on the QString.
QString provides the following four functions that return a const char * version of the string as QByteArray: toAscii(), toLatin1(), toUtf8(), and toLocal8Bit().
To convert from one of these encodings, QString provides fromAscii(), fromLatin1(), fromUtf8(), and fromLocal8Bit(). Other encodings are supported through the QTextCodec class.
As mentioned above, QString provides a lot of functions and operators that make it easy to interoperate with const char * strings. But this functionality is a double-edged sword: It makes QString more convenient to use if all strings are ASCII or Latin-1, but there is always the risk that an implicit conversion from or to const char * is done using the wrong 8-bit encoding. To minimize these risks, you can turn off these implicit conversions by defining the following two preprocessor symbols:
One way to define these preprocessor symbols globally for your application is to add the following entry to your qmake project file:
DEFINES += QT_NO_CAST_FROM_ASCII \
QT_NO_CAST_TO_ASCII
You then need to explicitly call fromAscii(), fromLatin1(), fromUtf8(), or fromLocal8Bit() to construct a QString from an 8-bit string, or use the lightweight QLatin1String class, for example:
QString url = QLatin1String("http://www.unicode.org/");
Similarly, you must call toAscii(), toLatin1(), toUtf8(), or toLocal8Bit() explicitly to convert the QString to an 8-bit string. (Other encodings are supported through the QTextCodec class.)
Note for C ProgrammersDue to C++'s type system and the fact that QString is implicitly shared, QStrings may be treated like ints or other basic types. For example: QString Widget::boolToString(bool b)
{
QString result;
if (b)
result = "True";
else
result = "False";
return result;
}
The result variable, is a normal variable allocated on the stack. When return is called, and because we're returning by value, the copy constructor is called and a copy of the string is returned. No actual copying takes place thanks to the implicit sharing. |
For historical reasons, QString distinguishes between a null string and an empty string. A null string is a string that is initialized using QString's default constructor or by passing (const char *)0 to the constructor. An empty string is any string with size 0. A null string is always empty, but an empty string isn't necessarily null:
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
All functions except isNull() treat null strings the same as empty strings. For example, toAscii().constData() returns a pointer to a '\0' character for a null string (not a null pointer), and QString() compares equal to QString(""). We recommend that you always use the isEmpty() function and avoid isNull().
See also fromRawData(), QChar, QLatin1String, QByteArray, and QStringRef.
Qt-style synonym for QString::const_iterator.
Qt-style synonym for QString::iterator.
This enum describes the various normalized forms of Unicode text.
| Constant | Value | Description |
|---|---|---|
| QString::NormalizationForm_D | 0 | Canonical Decomposition |
| QString::NormalizationForm_C | 1 | Canonical Decomposition followed by Canonical Composition |
| QString::NormalizationForm_KD | 2 | Compatibility Decomposition |
| QString::NormalizationForm_KC | 3 | Compatibility Decomposition followed by Canonical Composition |
See also normalized() and Unicode Standard Annex #15.
This enum specifies flags that can be used to affect various aspects of the section() function's behavior with respect to separators and empty fields.
| Constant | Value | Description |
|---|---|---|
| QString::SectionDefault | 0x00 | Empty fields are counted, leading and trailing separators are not included, and the separator is compared case sensitively. |
| QString::SectionSkipEmpty | 0x01 | Treat empty fields as if they don't exist, i.e. they are not considered as far as start and end are concerned. |
| QString::SectionIncludeLeadingSep | 0x02 | Include the leading separator (if any) in the result string. |
| QString::SectionIncludeTrailingSep | 0x04 | Include the trailing separator (if any) in the result string. |
| QString::SectionCaseInsensitiveSeps | 0x08 | Compare the separator case-insensitively. |
The SectionFlags type is a typedef for QFlags<SectionFlag>. It stores an OR combination of SectionFlag values.
See also section().
This enum specifies how the split() function should behave with respect to empty strings.
| Constant | Value | Description |
|---|---|---|
| QString::KeepEmptyParts | 0 | If a field is empty, keep it in the result. |
| QString::SkipEmptyParts | 1 | If a field is empty, don't include it in the result. |
See also split().
The QString::const_iterator typedef provides an STL-style const iterator for QString.
See also QString::iterator.
The QString::iterator typedef provides an STL-style non-const iterator for QString.
See also QString::const_iterator.
Constructs a null string. Null strings are also empty.
See also isEmpty().
Constructs a string initialized with the first size characters of the QChar array unicode.
QString makes a deep copy of the string data.
Constructs a string of size 1 containing the character ch.
Constructs a string of the given size with every character set to ch.
See also fill().
Constructs a copy of the Latin-1 string str.
See also fromLatin1().
Constructs a copy of other.
This operation takes constant time, because QString is implicitly shared. This makes returning a QString from a function very fast. If a shared instance is modified, it will be copied (copy-on-write), and that takes linear time.
See also operator=().
Constructs a string initialized with the ASCII string str. The given const char pointer is converted to Unicode using the fromAscii() function.
You can disable this constructor by defining QT_NO_CAST_FROM_ASCII when you compile your applications. This can be useful if you want to ensure that all user-visible strings go through QObject::tr(), for example.
See also fromAscii(), fromLatin1(), fromLocal8Bit(), and fromUtf8().
Constructs a string initialized with the byte array ba. The given byte array is converted to Unicode using fromAscii(). Stops copying at the first 0 character, otherwise copies the entire byte array.
You can disable this constructor by defining QT_NO_CAST_FROM_ASCII when you compile your applications. This can be useful if you want to ensure that all user-visible strings go through QObject::tr(), for example.
See also fromAscii(), fromLatin1(), fromLocal8Bit(), and fromUtf8().
Destroys the string.
Appends the string str onto the end of this string.
Example:
QString x = "free";
QString y = "dom";
x.append(y);
// x == "freedom"
This is the same as using the insert() function:
x.insert(x.size(), y);
The append() function is typically very fast (constant time), because QString preallocates extra space at the end of the string data so it can grow without reallocating the entire string each time.
See also operator+=(), prepend(), and insert().
This is an overloaded member function, provided for convenience.
Appends the given string reference to this string and returns the result.
This function was introduced in Qt 4.4.
This is an overloaded member function, provided for convenience.
Appends the Latin-1 string str to this string.
This is an overloaded member function, provided for convenience.
Appends the byte array ba to this string. The given byte array is converted to Unicode using the fromAscii() function.
You can disable this function by defining QT_NO_CAST_FROM_ASCII when you compile your applications. This can be useful if you want to ensure that all user-visible strings go through QObject::tr(), for example.
This is an overloaded member function, provided for convenience.
Appends the string str to this string. The given const char pointer is converted to Unicode using the fromAscii() function.
You can disable this function by defining QT_NO_CAST_FROM_ASCII when you compile your applications. This can be useful if you want to ensure that all user-visible strings go through QObject::tr(), for example.
This is an overloaded member function, provided for convenience.
Appends the character ch to this string.
This function returns a copy of this string where a replaces the lowest numbered occurrence of %1, %2, ..., %99.
The fieldWidth value specifies the minimum amount of space that a is padded to and filled with the character fillChar. A positive value will produce right-aligned text, whereas a negative value will produce left-aligned text.
The following example shows how we could create a 'status' string when processing a list of files:
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);
One advantage of using arg() over sprintf() is that the order of arguments may need to change in other languages, when the application is translated.
If there is no place marker (%1, %2, etc.), a warning message is output and the result is undefined. Note that only placeholders between %1 and %99 are supported.
This is an overloaded member function, provided for convenience.
This is the same as str.arg(a1).arg(a2), except that the strings a1 and a2 are replaced in one pass. This can make a difference if a1 contains e.g. %1:
QString str;
str = "%1 %2";
str.arg("%1f", "Hello"); // returns "%1f Hello"
str.arg("%1f").arg("Hello"); // returns "Hellof %2"
This is an overloaded member function, provided for convenience.
This is the same as calling str.arg(a1).arg(a2).arg(a3), except that the strings a1, a2 and a3 are replaced in one pass.
This is an overloaded member function, provided for convenience.
This is the same as calling str.arg(a1).arg(a2).arg(a3).arg(a4), except that the strings a1, a2, a3 and a4 are replaced in one pass.
This is an overloaded member function, provided for convenience.
This is the same as calling str.arg(a1).arg(a2).arg(a3).arg(a4).arg(a5), except that the strings a1, a2, a3, a4, and a5 are replaced in one pass.
This is an overloaded member function, provided for convenience.
This is the same as calling str.arg(a1).arg(a2).arg(a3).arg(a4).arg(a5).arg(a6)), except that the strings a1, a2, a3, a4, a5, and a6 are replaced in one pass.
This is an overloaded member function, provided for convenience.
This is the same as calling str.arg(a1).arg(a2).arg(a3).arg(a4).arg(a5).arg(a6).arg(a7), except that the strings a1, a2, a3, a4, a5, a6, and a7 are replaced in one pass.
This is an overloaded member function, provided for convenience.
This is the same as calling str.arg(a1).arg(a2).arg(a3).arg(a4).arg(a5).arg(a6).arg(a7).arg(a8), except that the strings a1, a2, a3, a4, a5, a6, a7, and a8 are replaced in one pass.
This is an overloaded member function, provided for convenience.
This is the same as calling str.arg(a1).arg(a2).arg(a3).arg(a4).arg(a5).arg(a6).arg(a7).arg(a8).arg(a9), except that the strings a1, a2, a3, a4, a5, a6, a7, a8, and a9 are replaced in one pass.
This is an overloaded member function, provided for convenience.
The a argument is expressed in base base, which is 10 by default and must be between 2 and 36. For bases other than 10, a is treated as an unsigned integer.
The fieldWidth value specifies the minimum amount of space that a is padded to and filled with the character fillChar. A positive value will produce a right-aligned number, whereas a negative value will produce a left-aligned number.
The '%' can be followed by an 'L', in which case the sequence is replaced with a localized representation of a. The conversion uses the default locale, set by QLocale::setDefault(). If no default locale was specified, the "C" locale is used. The 'L' flag is ignored if base is not 10.
QString str;
str = QString("Decimal 63 is %1 in hexadecimal")
.arg(63, 0, 16);
// str == "Decimal 63 is 3f in hexadecimal"
QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedStates));
str = QString("%1 %L2 %L3")
.arg(12345)
.arg(12345)
.arg(12345, 0, 16);
// str == "12345 12,345 3039"
This is an overloaded member function, provided for convenience.
The base argument specifies the base to use when converting the integer a into a string. The base must be between 2 and 36.
This is an overloaded member function, provided for convenience.
The fieldWidth value specifies the minimum amount of space that a is padded to and filled with the character fillChar. A positive value will produce a right-aligned number, whereas a negative value will produce a left-aligned number.
The a argument is expressed in the given base, which is 10 by default and must be between 2 and 36.
The '%' can be followed by an 'L', in which case the sequence is replaced with a localized representation of a. The conversion uses the default locale. The default locale is determined from the system's locale settings at application startup. It can be changed using QLocale::setDefault(). The 'L' flag is ignored if base is not 10.
QString str;
str = QString("Decimal 63 is %1 in hexadecimal")
.arg(63, 0, 16);
// str == "Decimal 63 is 3f in hexadecimal"
QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedStates));
str = QString("%1 %L2 %L3")
.arg(12345)
.arg(12345)
.arg(12345, 0, 16);
// str == "12345 12,345 3039"
This is an overloaded member function, provided for convenience.
The base argument specifies the base to use when converting the integer a into a string. The base must be between 2 and 36, with 8 giving octal, 10 decimal, and 16 hexadecimal numbers.
This is an overloaded member function, provided for convenience.
The base argument specifies the base to use when converting the integer a into a string. The base must be between 2 and 36, with 8 giving octal, 10 decimal, and 16 hexadecimal numbers.
This is an overloaded member function, provided for convenience.
The base argument specifies the base to use when converting the integer a into a string. base must be between 2 and 36, with 8 giving octal, 10 decimal, and 16 hexadecimal numbers.
This is an overloaded member function, provided for convenience.
The base argument specifies the base to use when converting the integer a into a string. The base must be between 2 and 36, with 8 giving octal, 10 decimal, and 16 hexadecimal numbers.
This is an overloaded member function, provided for convenience.
The base argument specifies the base to use when converting the integer a into a string. The base must be between 2 and 36, with 8 giving octal, 10 decimal, and 16 hexadecimal numbers.
This is an overloaded member function, provided for convenience.
This is an overloaded member function, provided for convenience.
The a argument is interpreted as a Latin-1 character.
This is an overloaded member function, provided for convenience.
Argument a is formatted according to the specified format, which is 'g' by default and can be any of the following:
| Format | Meaning |
|---|---|
| e | format as [-]9.9e[+|-]999 |
| E | format as [-]9.9E[+|-]999 |
| f | format as [-]9.9 |
| g | use e or f format, whichever is the most concise |
| G | use E or f format, whichever is the most concise |
With 'e', 'E', and 'f', precision is the number of digits after the decimal point. With 'g' and 'G', precision is the maximum number of significant digits (trailing zeroes are omitted).
double d = 12.34;
QString str = QString("delta: %1").arg(d, 0, 'E', 3);
// str == "delta: 1.234E+01"
The '%' can be followed by an 'L', in which case the sequence is replaced with a localized representation of a. The conversion uses the default locale, set by QLocale::setDefaultLocale(). If no default locale was specified, the "C" locale is used.
See also QLocale::toString().
Returns the character at the given index position in the string.
The position must be a valid index position in the string (i.e., 0 <= position < size()).
See also operator[]().
Returns an STL-style iterator pointing to the first character in the string.
See also constBegin() and end().
This is an overloaded member function, provided for convenience.
Returns the maximum number of characters that can be stored in the string without forcing a reallocation.
The sole purpose of this function is to provide a means of fine tuning QString's memory usage. In general, you will rarely ever need to call this function. If you want to know how many characters are in the string, call size().
See also reserve() and squeeze().
Removes n characters from the end of the string.
If n is greater than size(), the result is an empty string.
Example:
QString str("LOGOUT\r\n");
str.chop(2);
// str == "LOGOUT"
If you want to remove characters from the beginning of the string, use remove() instead.
See also truncate(), resize(), and remove().
Clears the contents of the string and makes it empty.
See also resize() and isEmpty().
Compares s1 with s2 and returns an integer less than, equal to, or greater than zero if s1 is less than, equal to, or greater than s2.
If cs is Qt::CaseSensitive, the comparison is case sensitive; otherwise the comparison is case insensitive.
Case sensitive comparison is based exclusively on the numeric Unicode values of the characters and is very fast, but is not what a human would expect. Consider sorting user-visible strings with localeAwareCompare().
int x = QString::compare("aUtO", "AuTo", Qt::CaseInsensitive); // x == 0
int y = QString::compare("auto", "Car", Qt::CaseSensitive); // y > 0
int z = QString::compare("auto", "Car", Qt::CaseInsensitive); // z < 0
This function was introduced in Qt 4.2.
See also operator==(), operator<(), and operator>().
This is an overloaded member function, provided for convenience.
Performs a case sensitive compare of s1 and s2.
This is an overloaded member function, provided for convenience.
Performs a comparison of s1 and s2, using the case sensitivity setting cs.
This function was introduced in Qt 4.2.
This is an overloaded member function, provided for convenience.
Performs a comparison of s1 and s2, using the case sensitivity setting cs.
This function was introduced in Qt 4.2.
This is an overloaded member function, provided for convenience.
Lexically compares this string with the other string and returns an integer less than, equal to, or greater than zero if this string is less than, equal to, or greater than the other string.
Equivalent to compare(*this, other).
This is an overloaded member function, provided for convenience.
Same as compare(*this, other, cs).
This function was introduced in Qt 4.2.
This is an overloaded member function, provided for convenience.
Same as compare(*this, other, cs).
This function was introduced in Qt 4.2.
Returns a const STL-style iterator pointing to the first character in the string.
See also begin() and constEnd().
Returns a pointer to the data stored in the QString. The pointer can be used to access the characters that compose the string. For convenience, the data is '\0'-terminated.
Note that the pointer remains valid only as long as the string is not modified.
See also data() and operator[]().
Returns a const STL-style iterator pointing to the imaginary item after the last item in the list.
See also constBegin() and end().
Returns true if this string contains an occurrence of the string str; otherwise returns false.
If cs is Qt::CaseSensitive (the default), the search is case sensitive; otherwise the search is case insensitive.
Example:
QString str = "Peter Pan";
str.contains("peter", Qt::CaseInsensitive); // returns true
See also indexOf() and count().
This is an overloaded member function, provided for convenience.
Returns true if this string contains an occurrence of the character ch; otherwise returns false.
This is an overloaded member function, provided for convenience.
Returns true if the regular expression rx matches somewhere in this string; otherwise returns false.
Returns the number of (potentially overlapping) occurrences of the string str in this string.
If cs is Qt::CaseSensitive (the default), the search is case sensitive; otherwise the search is case insensitive.
See also contains() and indexOf().
This is an overloaded member function, provided for convenience.
Returns the number of occurrences of character ch in the string.
This is an overloaded member function, provided for convenience.
Returns the number of times the regular expression rx matches in the string.
This function counts overlapping matches, so in the example below, there are four instances of "ana" or "ama":
QString str = "banana and panama";
str.count(QRegExp("a[nm]a")); // returns 4
This is an overloaded member function, provided for convenience.
Same as size().
Returns a pointer to the data stored in the QString. The pointer can be used to access and modify the characters that compose the string. For convenience, the data is '\0'-terminated.
Example:
QString str = "Hello world";
QChar *data = str.data();
while (!data->isNull()) {
qDebug() << data->unicode();
++data;
}
Note that the pointer remains valid only as long as the string is not modified by other means. For read-only access, constData() is faster because it never causes a deep copy to occur.
See also constData() and operator[]().
This is an overloaded member function, provided for convenience.
Returns an STL-style iterator pointing to the imaginary character after the last character in the string.
See also begin() and constEnd().
This is an overloaded member function, provided for convenience.
Returns true if the string ends with s; otherwise returns false.
If cs is Qt::CaseSensitive (the default), the search is case sensitive; otherwise the search is case insensitive.
QString str = "Bananas";
str.endsWith("anas"); // returns true
str.endsWith("pple"); // returns false
See also startsWith().
This is an overloaded member function, provided for convenience.
This is an overloaded member function, provided for convenience.
Returns true if the string ends with c; otherwise returns false.
Sets every character in the string to character ch. If size is different from -1 (the default), the string is resized to size beforehand.
Example:
QString str = "Berlin";
str.fill('z');
// str == "zzzzzz"
str.fill('A', 2);
// str == "AA"
See also resize().
Returns a QString initialized with the first size characters of the 8-bit ASCII string str.
If size is -1 (the default), it is taken to be qstrlen(str).
If a codec has been set using QTextCodec::setCodecForCStrings(), it is used to convert str to Unicode; otherwise this function does the same as fromLatin1().
See also toAscii(), fromLatin1(), fromUtf8(), and fromLocal8Bit().
Returns a QString initialized with the first size characters of the Latin-1 string str.
If size is -1 (the default), it is taken to be qstrlen(str).
See also toLatin1(), fromAscii(), fromUtf8(), and fromLocal8Bit().
Returns a QString initialized with the first size characters of the 8-bit string str.
If size is -1 (the default), it is taken to be qstrlen(str).
QTextCodec::codecForLocale() is used to perform the conversion from Unicode.
See also toLocal8Bit(), fromAscii(), fromLatin1(), and fromUtf8().
Constructs a QString that uses the first size Unicode characters in the array unicode. The data in unicode is not copied. The caller must be able to guarantee that unicode will not be deleted or modified as long as the QString (or an unmodified copy of it) exists.
Any attempts to modify the QString or copies of it will cause it to create a deep copy of the data, ensuring that the raw data isn't modified.
Here's an example of how we can use a QRegExp on raw data in memory without requiring to copy the data into a QString:
QRegExp pattern;
static const QChar unicode[] = {
0x005A, 0x007F, 0x00A4, 0x0060,
0x1009, 0x0020, 0x0020};
int size = sizeof(unicode) / sizeof(QChar);
QString str = QString::fromRawData(unicode, size);
if (str.contains(QRegExp(pattern))) {
// ...
}
Warning: A string created with fromRawData() is not '\0'-terminated, unless the raw data contains a '\0' character at position size. This means unicode() will not return a '\0'-terminated string (although utf16() does, at the cost of copying the raw data).
See also fromUtf16().
Returns a copy of the str string. The given string is converted to Unicode using the fromAscii() function.
This constructor is only available if Qt is configured with STL compatibility enabled.
See also fromAscii(), fromLatin1(), fromLocal8Bit(), and fromUtf8().
Returns a copy of the str string. The given string is assumed to be encoded in utf16 if the size of wchar_t is 2 bytes (e.g. on windows) and ucs4 if the size of wchar_t is 4 bytes (most Unix systems).
This method is only available if Qt is configured with STL compatibility enabled.
See also fromUtf16(), fromLatin1(), fromLocal8Bit(), fromUtf8(), and fromUcs4().
Returns a QString initialized with the first size characters of the Unicode string unicode (ISO-10646-UCS-4 encoded).
If size is -1 (the default), unicode must be terminated with a 0.
This function was introduced in Qt 4.2.
See also toUcs4(), fromUtf16(), utf16(), setUtf16(), and fromWCharArray().
Returns a QString initialized with the first size bytes of the UTF-8 string str.
If size is -1 (the default), it is taken to be qstrlen(str).
See also toUtf8(), fromAscii(), fromLatin1(), and fromLocal8Bit().
Returns a QString initialized with the first size characters of the Unicode string unicode (ISO-10646-UTF-16 encoded).
If size is -1 (the default), unicode must be terminated with a 0.
QString makes a deep copy of the Unicode data.
See also utf16() and setUtf16().
Returns a copy of the string string encoded in ucs4.
If size is -1 (the default), the string has to be 0 terminated.
This function was introduced in Qt 4.2.
See also fromUtf16(), fromLatin1(), fromLocal8Bit(), fromUtf8(), fromUcs4(), and fromStdWString().
Returns the index position of the first occurrence of the string str in this string, searching forward from index position from. Returns -1 if str is not found.
If cs is Qt::CaseSensitive (the default), the search is case sensitive; otherwise the search is case insensitive.
Example:
QString x = "sticky question";
QString y = "sti";
x.indexOf(y); // returns 0
x.indexOf(y, 1); // returns 10
x.indexOf(y, 10); // returns 10
x.indexOf(y, 11); // returns -1
If from is -1, the search starts at the last character; if it is -2, at the next to last character and so on.
See also lastIndexOf(), contains(), and count().
This is an overloaded member function, provided for convenience.
Returns the index position of the first occurrence of the character ch in the string, searching forward from index position from. Returns -1 if ch could not be found.
This is an overloaded member function, provided for convenience.
Returns the index position of the first match of the regular expression rx in the string, searching forward from index position from. Returns -1 if rx didn't match anywhere.
Example:
QString str = "the minimum";
str.indexOf(QRegExp("m[aeiou]"), 0); // returns 4
Inserts the string str at the given index position and returns a reference to this string.
Example:
QString str = "Meal";
str.insert(1, QString("ontr"));
// str == "Montreal"
If the given position is greater than size(), the array is first extended using resize().
See also append(), prepend(), replace(), and remove().
This is an overloaded member function, provided for convenience.
Inserts the Latin-1 string str at the given index position.
This is an overloaded member function, provided for convenience.
Inserts the first size characters of the QChar array unicode at the given index position in the string.
This is an overloaded member function, provided for convenience.
Inserts ch at the given index position in the string.
Returns true if the string has no characters; otherwise returns false.
Example:
QString().isEmpty(); // returns true QString("").isEmpty(); // returns true QString("x").isEmpty(); // returns false QString("abc").isEmpty(); // returns false
See also size().
Returns true if this string is null; otherwise returns false.
Example:
QString().isNull(); // returns true QString("").isNull(); // returns false QString("abc").isNull(); // returns false
Qt makes a distinction between null strings and empty strings for historical reasons. For most applications, what matters is whether or not a string contains any data, and this can be determined using the isEmpty() function.
See also isEmpty().
Returns the index position of the last occurrence of the string str in this string, searching backward from index position from. If from is -1 (the default), the search starts at the last character; if from is -2, at the next to last character and so on. Returns -1 if str is not found.
If cs is Qt::CaseSensitive (the default), the search is case sensitive; otherwise the search is case insensitive.
Example:
QString x = "crazy azimuths";
QString y = "az";
x.lastIndexOf(y); // returns 6
x.lastIndexOf(y, 6); // returns 6
x.lastIndexOf(y, 5); // returns 2
x.lastIndexOf(y, 1); // returns -1
See also indexOf(), contains(), and count().
This is an overloaded member function, provided for convenience.
Returns the index position of the last occurrence of the character ch, searching backward from position from.
This is an overloaded member function, provided for convenience.
Returns the index position of the last match of the regular expression rx in the string, searching backward from index position from. Returns -1 if rx didn't match anywhere.
Example:
QString str = "the minimum";
str.lastIndexOf(QRegExp("m[aeiou]")); // returns 8
Returns a substring that contains the n leftmost characters of the string.
The entire string is returned if n is greater than size() or less than zero.
QString x = "Pineapple";
QString y = x.left(4); // y == "Pine"
See also right(), mid(), and startsWith().
Returns a string of size width that contains this string padded by the fill character.
If truncate is false and the size() of the string is more than width, then the returned string is a copy of the string.
QString s = "apple";
QString t = s.leftJustified(8, '.'); // t == "apple..."
If truncate is true and the size() of the string is more than width, then any characters in a copy of the string after position width are removed, and the copy is returned.
QString str = "Pineapple";
str = str.leftJustified(5, '.', true); // str == "Pinea"
See also rightJustified().
Returns a substring reference to the n leftmost characters of the string.
If n is greater than size() or less than zero, a reference to the entire string is returned.
QString x = "Pineapple";
QStringRef y = x.leftRef(4); // y == "Pine"
This function was introduced in Qt 4.4.
See also left(), rightRef(), midRef(), and startsWith().
Returns the number of characters in this string. Equivalent to size().
See also setLength().
Compares s1 with s2 and returns an integer less than, equal to, or greater than zero if s1 is less than, equal to, or greater than s2.
The comparison is performed in a locale- and also platform-dependent manner. Use this function to present sorted lists of strings to the user.
On Mac OS X since Qt 4.3, this function compares according the "Order for sorted lists" setting in the International prefereces panel.
See also compare() and QTextCodec::locale().
This is an overloaded member function, provided for convenience.
Compares this string with the other string and returns an integer less than, equal to, or greater than zero if this string is less than, equal to, or greater than the other string.
Same as localeAwareCompare(*this, other).
Returns a string that contains n characters of this string, starting at the specified position index.
Returns a null string if the position index exceeds the length of the string. If there are less than n characters available in the string starting at the given position, or if n is -1 (the default), the function returns all characters that are available from the specified position.
Example:
QString x = "Nine pineapples";
QString y = x.mid(5, 4); // y == "pine"
QString z = x.mid(5); // z == "pineapples"
Returns a substring reference to n characters of this string, starting at the specified position.
If the position exceeds the length of the string, an empty reference is returned.
If there are less than n characters available in the string, starting at the given position, or if n is -1 (the default), the function returns all characters from the specified position onwards.
Example:
QString x = "Nine pineapples";
QStringRef y = x.midRef(5, 4); // y == "pine"
QStringRef z = x.midRef(5); // z == "pineapples"
This function was introduced in Qt 4.4.
See also mid(), leftRef(), and rightRef().
Returns the string in the given Unicode normalization mode.
This is an overloaded member function, provided for convenience.
Returns the string in the given Unicode normalization mode, according to the given version of the Unicode standard.
Returns a string equivalent of the number n according to the specified base.
The base is 10 by default and must be between 2 and 36. For bases other than 10, n is treated as an unsigned integer.
long a = 63;
QString s = QString::number(a, 16); // s == "3f"
QString t = QString::number(a, 16).toUpper(); // t == "3F"
See also setNum().
This is an overloaded member function, provided for convenience.
This is an overloaded member function, provided for convenience.
This is an overloaded member function, provided for convenience.
This is an overloaded member function, provided for convenience.
This is an overloaded member function, provided for convenience.
This is an overloaded member function, provided for convenience.
Returns a string equivalent of the number n, formatted according to the specified format and precision. The format can be 'f', 'F', 'e', 'E', 'g' or 'G' (see the arg() function documentation for an explanation of the formats).
Unlike QLocale::toString(), this function does not honor the user's locale settings.
See also setNum() and QLocale::toString().
Prepends the string str to the beginning of this string and returns a reference to this string.
Example:
QString x = "ship";
QString y = "air";
x.prepend(y);
// x == "airship"
See also append() and insert().
This is an overloaded member function, provided for convenience.
Prepends the Latin-1 string str to this string.
This is an overloaded member function, provided for convenience.
Prepends the byte array ba to this string. The byte array is converted to Unicode using the fromAscii() function.
You can disable this function by defining QT_NO_CAST_FROM_ASCII when you compile your applications. This can be useful if you want to ensure that all user-visible strings go through QObject::tr(), for example.
This is an overloaded member function, provided for convenience.
Prepends the string str to this string. The const char pointer is converted to Unicode using the fromAscii() function.
You can disable this function by defining QT_NO_CAST_FROM_ASCII when you compile your applications. This can be useful if you want to ensure that all user-visible strings go through QObject::tr(), for example.
This is an overloaded member function, provided for convenience.
Prepends the character ch to this string.
This function is provided for STL compatibility, appending the given other string onto the end of this string. It is equivalent to append(other).
See also append().
This is an overloaded member function, provided for convenience.
Appends the given ch character onto the end of this string.
This function is provided for STL compatibility, prepending the given other string to the beginning of this string. It is equivalent to prepend(other).
See also prepend().
This is an overloaded member function, provided for convenience.
Prepends the given ch character to the beginning of this string.
Removes n characters from the string, starting at the given position index, and returns a reference to the string.
If the specified position index is within the string, but position + n is beyond the end of the string, the string is truncated at the specified position.
QString s = "Montreal";
s.remove(1, 4);
// s == "Meal"
See also insert() and replace().
This is an overloaded member function, provided for convenience.
Removes every occurrence of the given str string in this string, and returns a reference to this string.
If cs is Qt::CaseSensitive (the default), the search is case sensitive; otherwise the search is case insensitive.
This is the same as replace(str, "", cs).
See also replace().
This is an overloaded member function, provided for convenience.
Removes every occurrence of the character ch in this string, and returns a reference to this string.
If cs is Qt::CaseSensitive (the default), the search is case sensitive; otherwise the search is case insensitive.
Example:
QString t = "Ali Baba";
t.remove(QChar('a'), Qt::CaseInsensitive);
// t == "li Bb"
This is the same as replace(ch, "", cs).
See also replace().
This is an overloaded member function, provided for convenience.
Removes every occurrence of the regular expression rx in the string, and returns a reference to the string. For example:
QString r = "Telephone";
r.remove(QRegExp("[aeiou]."));
// r == "The"
See also indexOf(), lastIndexOf(), and replace().
Replaces n characters from the specified index position with the string after, and returns a reference to this string.
Example:
QString x = "Say yes!";
QString y = "no";
x.replace(4, 3, y);
// x == "Say no!"
See also insert() and remove().
This is an overloaded member function, provided for convenience.
Replaces n characters from the specified index position with the first size characters of the QChar array unicode.
This is an overloaded member function, provided for convenience.
Replaces n characters from the specified index position with the character after.
This is an overloaded member function, provided for convenience.
Replaces every occurrence of the string before with the string after.
If cs is Qt::CaseSensitive (the default), the search is case sensitive; otherwise the search is case insensitive.
Example:
QString str = "colour behaviour flavour neighbour";
str.replace(QString("ou"), QString("o"));
// str == "color behavior flavor neighbor"
Note: The replacement text is not rescanned after it is inserted.
Example:
QString equis = "xxxxxx";
equis.replace("xx", "x");
// equis == "xxx"
This is an overloaded member function, provided for convenience.
Replaces every occurrence of the character ch in the string with after. Returns a reference to the string.
If cs is Qt::CaseSensitive (the default), the search is case sensitive; otherwise the search is