QString Class

The QString class provides a Unicode character string. More...

Header: #include <QString>
qmake: QT += core

Note: All functions in this class are reentrant.

Public Types

typedef ConstIterator
typedef Iterator
enum NormalizationForm { NormalizationForm_D, NormalizationForm_C, NormalizationForm_KD, NormalizationForm_KC }
enum SectionFlag { SectionDefault, SectionSkipEmpty, SectionIncludeLeadingSep, SectionIncludeTrailingSep, SectionCaseInsensitiveSeps }
flags SectionFlags
enum SplitBehavior { KeepEmptyParts, SkipEmptyParts }
typedef const_iterator
typedef const_pointer
typedef const_reference
typedef const_reverse_iterator
typedef difference_type
typedef iterator
typedef pointer
typedef reference
typedef reverse_iterator
typedef size_type
typedef value_type

Public Functions

QString(int size, QChar ch)
QString(QChar ch)
QString(const QChar *unicode, int size = -1)
QString &append(const QString &str)
QString &append(QChar ch)
QString &append(const QChar *str, int len)
QString &append(QLatin1String str)
QString arg(qlonglong a, int fieldWidth = 0, int base = 10, QChar fillChar = QLatin1Char(' ')) const
QString arg(qulonglong a, int fieldWidth = 0, int base = 10, QChar fillChar = QLatin1Char(' ')) const
QString arg(char a, int fieldWidth = 0, QChar fillChar = QLatin1Char(' ')) const
QString arg(QChar a, int fieldWidth = 0, QChar fillChar = QLatin1Char(' ')) const
QString arg(const QString &a, int fieldWidth = 0, QChar fillChar = QLatin1Char(' ')) const
QString arg(QStringView a, int fieldWidth = 0, QChar fillChar = QLatin1Char(' ')) const
QString arg(QLatin1String a, int fieldWidth = 0, QChar fillChar = QLatin1Char(' ')) const
void chop(int n)
int compare(const QString &other, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
int compare(QLatin1String other, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
bool contains(const QRegularExpression &re) const
bool contains(const QRegularExpression &re, QRegularExpressionMatch *match) const
int count(QChar ch, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
int count(const QString &str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
int count(const QStringRef &str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
int count(const QRegExp &rx) const
int count(const QRegularExpression &re) const
bool endsWith(const QString &s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
bool endsWith(const QStringRef &s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
bool endsWith(QLatin1String s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
bool endsWith(QChar c, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
QString &fill(QChar ch, int size = -1)
int indexOf(const QString &str, int from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
int indexOf(QChar ch, int from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
int indexOf(QLatin1String str, int from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
int indexOf(const QStringRef &str, int from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
int indexOf(const QRegExp &rx, int from = 0) const
int indexOf(QRegExp &rx, int from = 0) const
int indexOf(const QRegularExpression &re, int from = 0) const
int indexOf(const QRegularExpression &re, int from, QRegularExpressionMatch *rmatch) const
bool isLower() const
bool isUpper() const
int lastIndexOf(const QString &str, int from = -1, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
int lastIndexOf(QChar ch, int from = -1, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
int lastIndexOf(QLatin1String str, int from = -1, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
int lastIndexOf(const QStringRef &str, int from = -1, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
int lastIndexOf(const QRegExp &rx, int from = -1) const
int lastIndexOf(QRegExp &rx, int from = -1) const
int lastIndexOf(const QRegularExpression &re, int from = -1) const
int lastIndexOf(const QRegularExpression &re, int from, QRegularExpressionMatch *rmatch) const
QString left(int n) const
QString leftJustified(int width, QChar fill = QLatin1Char(' '), bool truncate = false) const
QStringRef leftRef(int n) const
int localeAwareCompare(const QString &other) const
QString mid(int position, int n = -1) const
QStringRef midRef(int position, int n = -1) const
QString normalized(QString::NormalizationForm mode, QChar::UnicodeVersion version = QChar::Unicode_Unassigned) const
QString &remove(QChar ch, Qt::CaseSensitivity cs = Qt::CaseSensitive)
QString &remove(QLatin1String str, Qt::CaseSensitivity cs = Qt::CaseSensitive)
QString &remove(const QString &str, Qt::CaseSensitivity cs = Qt::CaseSensitive)
QString repeated(int times) const
QString &replace(QChar before, QChar after, Qt::CaseSensitivity cs = Qt::CaseSensitive)
QString &replace(const QChar *before, int blen, const QChar *after, int alen, Qt::CaseSensitivity cs = Qt::CaseSensitive)
QString &replace(QLatin1String before, QLatin1String after, Qt::CaseSensitivity cs = Qt::CaseSensitive)
QString &replace(QLatin1String before, const QString &after, Qt::CaseSensitivity cs = Qt::CaseSensitive)
QString &replace(const QString &before, QLatin1String after, Qt::CaseSensitivity cs = Qt::CaseSensitive)
QString &replace(const QString &before, const QString &after, Qt::CaseSensitivity cs = Qt::CaseSensitive)
QString &replace(QChar ch, const QString &after, Qt::CaseSensitivity cs = Qt::CaseSensitive)
QString &replace(QChar c, QLatin1String after, Qt::CaseSensitivity cs = Qt::CaseSensitive)
QString &replace(const QRegExp &rx, const QString &after)
QString &replace(const QRegularExpression &re, const QString &after)
void resize(int size)
void resize(int size, QChar fillChar)
QString right(int n) const
QString rightJustified(int width, QChar fill = QLatin1Char(' '), bool truncate = false) const
QStringRef rightRef(int n) const
QString section(const QString &sep, int start, int end = -1, QString::SectionFlags flags = SectionDefault) const
QString section(const QRegExp &reg, int start, int end = -1, QString::SectionFlags flags = SectionDefault) const
QString section(const QRegularExpression &re, int start, int end = -1, QString::SectionFlags flags = SectionDefault) const
QString &setNum(qlonglong n, int base = 10)
QString &setNum(qulonglong n, int base = 10)
QString &setRawData(const QChar *unicode, int size)
QString &setUnicode(const QChar *unicode, int size)
QStringList split(const QString &sep, QString::SplitBehavior behavior = KeepEmptyParts, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
QStringList split(QChar sep, QString::SplitBehavior behavior = KeepEmptyParts, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
QStringList split(const QRegExp &rx, QString::SplitBehavior behavior = KeepEmptyParts) const
QStringList split(const QRegularExpression &re, QString::SplitBehavior behavior = KeepEmptyParts) const
QVector<QStringRef> splitRef(const QString &sep, QString::SplitBehavior behavior = KeepEmptyParts, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
QVector<QStringRef> splitRef(QChar sep, QString::SplitBehavior behavior = KeepEmptyParts, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
QVector<QStringRef> splitRef(const QRegExp &rx, QString::SplitBehavior behavior = KeepEmptyParts) const
QVector<QStringRef> splitRef(const QRegularExpression &re, QString::SplitBehavior behavior = KeepEmptyParts) const
bool startsWith(const QString &s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
bool startsWith(const QStringRef &s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
bool startsWith(QLatin1String s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
bool startsWith(QChar c, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
CFStringRef toCFString() const
double toDouble(bool *ok = nullptr) const
float toFloat(bool *ok = nullptr) const
QString toHtmlEscaped() const
int toInt(bool *ok = nullptr, int base = 10) const
qlonglong toLongLong(bool *ok = nullptr, int base = 10) const
NSString *toNSString() const
short toShort(bool *ok = nullptr, int base = 10) const
uint toUInt(bool *ok = nullptr, int base = 10) const
qulonglong toULongLong(bool *ok = nullptr, int base = 10) const
ushort toUShort(bool *ok = nullptr, int base = 10) const
QVector<uint> toUcs4() const
bool operator<(QLatin1String other) const
QString &operator=(QChar ch)
bool operator==(QLatin1String other) const
bool operator>(QLatin1String other) const

Static Public Members

QString asprintf(const char *cformat, ...)
QString fromCFString(CFStringRef string)
QString fromNSString(const NSString *string)
QString fromRawData(const QChar *unicode, int size)
QString fromUcs4(const uint *unicode, int size = -1)
QString fromUtf16(const ushort *unicode, int size = -1)
QString number(int n, int base = 10)
QString number(uint n, int base = 10)
QString number(qlonglong n, int base = 10)
QString number(qulonglong n, int base = 10)
bool operator!=(const int &s1, const int &s2)
bool operator<(const QString &s1, const QString &s2)
bool operator==(const QString &s1, const QString &s2)

Macros

Detailed Description

QString stores a string of 16-bit QChars, where each QChar corresponds to one UTF-16 code unit. (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 US-ASCII (ANSI X3.4-1986) and Latin-1 (ISO 8859-1), and all the US-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 (like in embedded systems).

Initializing a String

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 fromUtf8() function.

In all of the QString functions that take const char * parameters, the const char * is interpreted as a classic C-style '\0'-terminated string encoded in UTF-8. 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().

Manipulating String Data

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 is 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::filter() function.

Querying String Data

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.

Converting Between 8-Bit Strings and Unicode Strings

QString provides the following three functions that return a const char * version of the string as QByteArray: toUtf8(), toLatin1(), and toLocal8Bit().

  • toLatin1() returns a Latin-1 (ISO 8859-1) encoded 8-bit string.
  • toUtf8() returns a UTF-8 encoded 8-bit string. UTF-8 is a superset of US-ASCII (ANSI X3.4-1986) that supports the entire Unicode character set through multibyte sequences.
  • toLocal8Bit() returns an 8-bit string using the system's local encoding.

To convert from one of these encodings, QString provides 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 US-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:

  • QT_NO_CAST_FROM_ASCII disables automatic conversions from C string literals and pointers to Unicode.
  • QT_RESTRICTED_CAST_FROM_ASCII allows automatic conversions from C characters and character arrays, but disables automatic conversions from character pointers to Unicode.
  • QT_NO_CAST_TO_ASCII disables automatic conversion from QString to C strings.

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 fromUtf8(), fromLatin1(), 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 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 Programmers
Due 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.

Distinction Between Null and Empty Strings

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, toUtf8().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().

Argument Formats

In member functions where an argument format can be specified (e.g., arg(), number()), the argument format can be one of the following:

FormatMeaning
eformat as [-]9.9e[+|-]999
Eformat as [-]9.9E[+|-]999
fformat as [-]9.9
guse e or f format, whichever is the most concise
Guse E or f format, whichever is the most concise

A precision is also specified with the argument format. For the 'e', 'E', and 'f' formats, the precision represents the number of digits after the decimal point. For the 'g' and 'G' formats, the precision represents the maximum number of significant digits (trailing zeroes are omitted).

More Efficient String Construction

Many strings are known at compile time. But the trivial constructor QString("Hello"), will copy the contents of the string, treating the contents as Latin-1. To avoid this one can use the QStringLiteral macro to directly create the required data at compile time. Constructing a QString out of the literal does then not cause any overhead at runtime.

A slightly less efficient way is to use QLatin1String. This class wraps a C string literal, precalculates it length at compile time and can then be used for faster comparison with QStrings and conversion to QStrings than a regular C string literal.

Using the QString '+' operator, it is easy to construct a complex string from multiple substrings. You will often write code like this:


      QString foo;
      QString type = "long";

      foo->setText(QLatin1String("vector<") + type + QLatin1String(">::iterator"));

      if (foo.startsWith("(" + type + ") 0x"))
          ...

There is nothing wrong with either of these string constructions, but there are a few hidden inefficiencies. Beginning with Qt 4.6, you can eliminate them.

First, multiple uses of the '+' operator usually means multiple memory allocations. When concatenating n substrings, where n > 2, there can be as many as n - 1 calls to the memory allocator.

In 4.6, an internal template class QStringBuilder has been added along with a few helper functions. This class is marked internal and does not appear in the documentation, because you aren't meant to instantiate it in your code. Its use will be automatic, as described below. The class is found in src/corelib/tools/qstringbuilder.cpp if you want to have a look at it.

QStringBuilder uses expression templates and reimplements the '%' operator so that when you use '%' for string concatenation instead of '+', multiple substring concatenations will be postponed until the final result is about to be assigned to a QString. At this point, the amount of memory required for the final result is known. The memory allocator is then called once to get the required space, and the substrings are copied into it one by one.

Additional efficiency is gained by inlining and reduced reference counting (the QString created from a QStringBuilder typically has a ref count of 1, whereas QString::append() needs an extra test).

There are two ways you can access this improved method of string construction. The straightforward way is to include QStringBuilder wherever you want to use it, and use the '%' operator instead of '+' when concatenating strings:


      #include <QStringBuilder>

      QString hello("hello");
      QStringRef el(&hello, 2, 3);
      QLatin1String world("world");
      QString message =  hello % el % world % QChar('!');

A more global approach which is the most convenient but not entirely source compatible, is to this define in your .pro file:


      DEFINES *= QT_USE_QSTRINGBUILDER

and the '+' will automatically be performed as the QStringBuilder '%' everywhere.

See also fromRawData(), QChar, QLatin1String, QByteArray, and QStringRef.

Member Type Documentation

typedef QString::ConstIterator

Qt-style synonym for QString::const_iterator.

typedef QString::Iterator

Qt-style synonym for QString::iterator.

enum QString::NormalizationForm

This enum describes the various normalized forms of Unicode text.

ConstantValueDescription
QString::NormalizationForm_D0Canonical Decomposition
QString::NormalizationForm_C1Canonical Decomposition followed by Canonical Composition
QString::NormalizationForm_KD2Compatibility Decomposition
QString::NormalizationForm_KC3Compatibility Decomposition followed by Canonical Composition

See also normalized() and Unicode Standard Annex #15.

enum QString::SectionFlag
flags QString::SectionFlags

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.

ConstantValueDescription
QString::SectionDefault0x00Empty fields are counted, leading and trailing separators are not included, and the separator is compared case sensitively.
QString::SectionSkipEmpty0x01Treat empty fields as if they don't exist, i.e. they are not considered as far as start and end are concerned.
QString::SectionIncludeLeadingSep0x02Include the leading separator (if any) in the result string.
QString::SectionIncludeTrailingSep0x04Include the trailing separator (if any) in the result string.
QString::SectionCaseInsensitiveSeps0x08Compare the separator case-insensitively.

The SectionFlags type is a typedef for QFlags<SectionFlag>. It stores an OR combination of SectionFlag values.

See also section().

enum QString::SplitBehavior

This enum specifies how the split() function should behave with respect to empty strings.

ConstantValueDescription
QString::KeepEmptyParts0If a field is empty, keep it in the result.
QString::SkipEmptyParts1If a field is empty, don't include it in the result.

See also split().

typedef QString::const_iterator

This typedef provides an STL-style const iterator for QString.

See also QString::iterator.

typedef QString::const_pointer

The QString::const_pointer typedef provides an STL-style const pointer to a QString element (QChar).

typedef QString::const_reference

This typedef provides an STL-style const reference for a QString element (QChar).

typedef QString::const_reverse_iterator

This typedef provides an STL-style const reverse iterator for QString.

This typedef was introduced in Qt 5.6.

See also QString::reverse_iterator and QString::const_iterator.

typedef QString::difference_type

The QString::size_type typedef provides an STL-style type for difference between pointers.

typedef QString::iterator

The QString::iterator typedef provides an STL-style non-const iterator for QString.

See also QString::const_iterator.

typedef QString::pointer

The QString::const_pointer typedef provides an STL-style pointer to a QString element (QChar).

typedef QString::reference

This typedef provides an STL-style reference for a QString element (QChar).

typedef QString::reverse_iterator

This typedef provides an STL-style non-const reverse iterator for QString.

This typedef was introduced in Qt 5.6.

See also QString::const_reverse_iterator and QString::iterator.

typedef QString::size_type

The QString::size_type typedef provides an STL-style type for sizes (int).

typedef QString::value_type

This typedef provides an STL-style value type for QString.

Member Function Documentation

QString::QString(int size, QChar ch)

Constructs a string of the given size with every character set to ch.

See also fill().

QString::QString(QChar ch)

Constructs a string of size 1 containing the character ch.

QString::QString(const QChar *unicode, int size = -1)

Constructs a string initialized with the first size characters of the QChar array unicode.

If unicode is 0, a null string is constructed.

If size is negative, unicode is assumed to point to a nul-terminated array and its length is determined dynamically. The terminating nul-character is not considered part of the string.

QString makes a deep copy of the string data. The unicode data is copied as is and the Byte Order Mark is preserved if present.

See also fromRawData().

QString &QString::append(const QString &str)

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().

QString &QString::append(QChar ch)

This function overloads append().

Appends the character ch to this string.

QString &QString::append(const QChar *str, int len)

This function overloads append().

Appends len characters from the QChar array str to this string.

This function was introduced in Qt 5.0.

QString &QString::append(QLatin1String str)

This function overloads append().

Appends the Latin-1 string str to this string.

QString QString::arg(qlonglong a, int fieldWidth = 0, int base = 10, QChar fillChar = QLatin1Char(' ')) const

This function overloads arg().

fieldWidth specifies the minimum amount of space that a is padded to and filled with the character fillChar. A positive value produces right-aligned text; a negative value produces left-aligned text.

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.

If fillChar is '0' (the number 0, ASCII 48), the locale's zero is used. For negative numbers, zero padding might appear before the minus sign.

QString QString::arg(qulonglong a, int fieldWidth = 0, int base = 10, QChar fillChar = QLatin1Char(' ')) const

This function overloads arg().

fieldWidth specifies the minimum amount of space that a is padded to and filled with the character fillChar. A positive value produces right-aligned text; a negative value produces left-aligned text.

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.

If fillChar is '0' (the number 0, ASCII 48), the locale's zero is used. For negative numbers, zero padding might appear before the minus sign.

QString QString::arg(char a, int fieldWidth = 0, QChar fillChar = QLatin1Char(' ')) const

This function overloads arg().

The a argument is interpreted as a Latin-1 character.

QString QString::arg(QChar a, int fieldWidth = 0, QChar fillChar = QLatin1Char(' ')) const

This function overloads arg().

QString QString::arg(const QString &a, int fieldWidth = 0, QChar fillChar = QLatin1Char(' ')) const

Returns a copy of this string with the lowest numbered place marker replaced by string a, i.e., %1, %2, ..., %99.

fieldWidth specifies the minimum amount of space that argument a shall occupy. If a requires less space than fieldWidth, it is padded to fieldWidth with character fillChar. A positive fieldWidth produces right-aligned text. A negative fieldWidth produces left-aligned text.

This example shows how we might create a status string for reporting progress while 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);

First, arg(i) replaces %1. Then arg(total) replaces %2. Finally, arg(fileName) replaces %3.

One advantage of using arg() over asprintf() is that the order of the numbered place markers can change, if the application's strings are translated into other languages, but each arg() will still replace the lowest numbered unreplaced place marker, no matter where it appears. Also, if place marker %i appears more than once in the string, the arg() replaces all of them.

If there is no unreplaced place marker remaining, a warning message is output and the result is undefined. Place marker numbers must be in the range 1 to 99.

QString QString::arg(QStringView a, int fieldWidth = 0, QChar fillChar = QLatin1Char(' ')) const

This is an overloaded function.

Returns a copy of this string with the lowest-numbered place-marker replaced by string a, i.e., %1, %2, ..., %99.

fieldWidth specifies the minimum amount of space that a shall occupy. If a requires less space than fieldWidth, it is padded to fieldWidth with character fillChar. A positive fieldWidth produces right-aligned text. A negative fieldWidth produces left-aligned text.

This example shows how we might create a status string for reporting progress while processing a list of files:


  int i;                // current file's number
  int total;            // number of files to process
  QStringView fileName; // current file's name

  QString status = QString("Processing file %1 of %2: %3")
                  .arg(i).arg(total).arg(fileName);

First, arg(i) replaces %1. Then arg(total) replaces %2. Finally, arg(fileName) replaces %3.

One advantage of using arg() over asprintf() is that the order of the numbered place markers can change, if the application's strings are translated into other languages, but each arg() will still replace the lowest-numbered unreplaced place-marker, no matter where it appears. Also, if place-marker %i appears more than once in the string, arg() replaces all of them.

If there is no unreplaced place-marker remaining, a warning message is printed and the result is undefined. Place-marker numbers must be in the range 1 to 99.

This function was introduced in Qt 5.10.

QString QString::arg(QLatin1String a, int fieldWidth = 0, QChar fillChar = QLatin1Char(' ')) const

This is an overloaded function.

Returns a copy of this string with the lowest-numbered place-marker replaced by string a, i.e., %1, %2, ..., %99.

fieldWidth specifies the minimum amount of space that a shall occupy. If a requires less space than fieldWidth, it is padded to fieldWidth with character fillChar. A positive fieldWidth produces right-aligned text. A negative fieldWidth produces left-aligned text.

One advantage of using arg() over asprintf() is that the order of the numbered place markers can change, if the application's strings are translated into other languages, but each arg() will still replace the lowest-numbered unreplaced place-marker, no matter where it appears. Also, if place-marker %i appears more than once in the string, arg() replaces all of them.

If there is no unreplaced place-marker remaining, a warning message is printed and the result is undefined. Place-marker numbers must be in the range 1 to 99.

This function was introduced in Qt 5.10.

[static] QString QString::asprintf(const char *cformat, ...)

Safely builds a formatted string from the format string cformat and an arbitrary list of arguments.

The format string supports the conversion specifiers, length modifiers, and flags provided by printf() in the standard C++ library. The cformat string and %s arguments must be UTF-8 encoded.

Note: The %lc escape sequence expects a unicode character of type char16_t, or ushort (as returned by QChar::unicode()). The %ls escape sequence expects a pointer to a zero-terminated array of unicode characters of type char16_t, or ushort (as returned by QString::utf16()). This is at odds with the printf() in the standard C++ library, which defines %lc to print a wchar_t and %ls to print a wchar_t*, and might also produce compiler warnings on platforms where the size of wchar_t is not 16 bits.

Warning: We do not recommend using QString::asprintf() in new Qt code. Instead, consider using QTextStream or arg(), both of which support Unicode strings seamlessly and are type-safe. Here is an example that uses QTextStream:


  QString result;
  QTextStream(&result) << "pi = " << 3.14;
  // result == "pi = 3.14"

For translations, especially if the strings contains more than one escape sequence, you should consider using the arg() function instead. This allows the order of the replacements to be controlled by the translator.

This function was introduced in Qt 5.5.

See also arg().

void QString::chop(int n)

Removes n characters from the end of the string.

If n is greater than or equal to size(), the result is an empty string; if n is negative, it is equivalent to passing zero.

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(), remove(), and QStringRef::chop().

int QString::compare(const QString &other, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

This function overloads compare().

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.

Same as compare(*this, other, cs).

This function was introduced in Qt 4.2.

int QString::compare(QLatin1String other, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

This function overloads compare().

Same as compare(*this, other, cs).

This function was introduced in Qt 4.2.

bool QString::contains(const QRegularExpression &re) const

This function overloads contains().

Returns true if the regular expression re matches somewhere in this string; otherwise returns false.

This function was introduced in Qt 5.0.

bool QString::contains(const QRegularExpression &re, QRegularExpressionMatch *match) const

This function overloads contains().

Returns true if the regular expression re matches somewhere in this string; otherwise returns false.

If the match is successful and match is not a null pointer, it also writes the results of the match into the QRegularExpressionMatch object pointed to by match.

This function was introduced in Qt 5.1.

See also QRegularExpression::match().

int QString::count(QChar ch, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

This function overloads count().

Returns the number of occurrences of character ch in the string.

If cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.

See also contains() and indexOf().

int QString::count(const QString &str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

Returns the number of (potentially overlapping) occurrences of the string str in this string.

If cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.

See also contains() and indexOf().

int QString::count(const QStringRef &str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

This function overloads count().

Returns the number of (potentially overlapping) occurrences of the string reference str in this string.

If cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.

This function was introduced in Qt 4.8.

See also contains() and indexOf().

int QString::count(const QRegExp &rx) const

This function overloads count().

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

int QString::count(const QRegularExpression &re) const

This function overloads count().

Returns the number of times the regular expression re 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(QRegularExpression("a[nm]a"));    // returns 4

This function was introduced in Qt 5.0.

bool QString::endsWith(const QString &s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

Returns true if the string ends with s; otherwise returns false.

If cs is Qt::CaseSensitive (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().

bool QString::endsWith(const QStringRef &s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

This function overloads endsWith().

Returns true if the string ends with the string reference s; otherwise returns false.

If cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.

This function was introduced in Qt 4.8.

See also startsWith().

bool QString::endsWith(QLatin1String s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

This function overloads endsWith().

bool QString::endsWith(QChar c, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

Returns true if the string ends with c; otherwise returns false.

This function overloads endsWith().

QString &QString::fill(QChar ch, int size = -1)

Sets every character in the string to character ch. If size is different from -1 (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().

[static] QString QString::fromCFString(CFStringRef string)

Constructs a new QString containing a copy of the string CFString.

Note: this function is only available on OS X and iOS.

This function was introduced in Qt 5.2.

[static] QString QString::fromNSString(const NSString *string)

Constructs a new QString containing a copy of the string NSString.

Note: this function is only available on OS X and iOS.

This function was introduced in Qt 5.2.

[static] QString QString::fromRawData(const QChar *unicode, int size)

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 is an example of how we can use a QRegularExpression on raw data in memory without requiring to copy the data into a QString:


  QRegularExpression pattern("\u00A4");
  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(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() and setRawData().

[static] QString QString::fromUcs4(const uint *unicode, int size = -1)

Returns a QString initialized with the first size characters of the Unicode string unicode (ISO-10646-UCS-4 encoded).

If size is -1 (default), unicode must be terminated with a 0.

This function was introduced in Qt 4.2.

See also toUcs4(), fromUtf16(), utf16(), setUtf16(), fromWCharArray(), and fromStdU32String().

[static] QString QString::fromUtf16(const ushort *unicode, int size = -1)

Returns a QString initialized with the first size characters of the Unicode string unicode (ISO-10646-UTF-16 encoded).

If size is -1 (default), unicode must be terminated with a 0.

This function checks for a Byte Order Mark (BOM). If it is missing, host byte order is assumed.

This function is slow compared to the other Unicode conversions. Use QString(const QChar *, int) or QString(const QChar *) if possible.

QString makes a deep copy of the Unicode data.

See also utf16(), setUtf16(), and fromStdU16String().

int QString::indexOf(const QString &str, int from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

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 (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().

int QString::indexOf(QChar ch, int from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

This function overloads indexOf().

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.

int QString::indexOf(QLatin1String str, int from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

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 (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.

This function was introduced in Qt 4.5.

See also lastIndexOf(), contains(), and count().

int QString::indexOf(const QStringRef &str, int from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

This function overloads indexOf().

Returns the index position of the first occurrence of the string reference str in this string, searching forward from index position from. Returns -1 if str is not found.

If cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.

This function was introduced in Qt 4.8.

int QString::indexOf(const QRegExp &rx, int from = 0) const

This function overloads indexOf().

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

int QString::indexOf(QRegExp &rx, int from = 0) const

This function overloads indexOf().

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.

If there is a match, the rx regular expression will contain the matched captures (see QRegExp::matchedLength, QRegExp::cap).

Example:


  QString str = "the minimum";
  str.indexOf(QRegExp("m[aeiou]"), 0);       // returns 4

This function was introduced in Qt 4.5.

int QString::indexOf(const QRegularExpression &re, int from = 0) const

This function overloads indexOf().

Returns the index position of the first match of the regular expression re in the string, searching forward from index position from. Returns -1 if re didn't match anywhere.

Example:


  QString str = "the minimum";
  str.indexOf(QRegularExpression("m[aeiou]"), 0);       // returns 4

This function was introduced in Qt 5.0.

int QString::indexOf(const QRegularExpression &re, int from, QRegularExpressionMatch *rmatch) const

This is an overloaded function.

Returns the index position of the first match of the regular expression re in the string, searching forward from index position from. Returns -1 if re didn't match anywhere.

If the match is successful and rmatch is not a null pointer, it also writes the results of the match into the QRegularExpressionMatch object pointed to by rmatch.

Example:


  QString str = "the minimum";
  QRegularExpressionMatch match;
  str.indexOf(QRegularExpression("m[aeiou]"), 0, &match);       // returns 4
  // match.captured() == mi

This function was introduced in Qt 5.5.

bool QString::isLower() const

Returns true if the string only contains lowercase letters, otherwise returns false.

This function was introduced in Qt 5.12.

See also QChar::isLower() and isUpper().

bool QString::isUpper() const

Returns true if the string only contains uppercase letters, otherwise returns false.

This function was introduced in Qt 5.12.

See also QChar::isUpper() and isLower().

int QString::lastIndexOf(const QString &str, int from = -1, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

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 (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 (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().

int QString::lastIndexOf(QChar ch, int from = -1, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

This function overloads lastIndexOf().

Returns the index position of the last occurrence of the character ch, searching backward from position from.

int QString::lastIndexOf(QLatin1String str, int from = -1, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

This function overloads lastIndexOf().

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 (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 (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

This function was introduced in Qt 4.5.

See also indexOf(), contains(), and count().

int QString::lastIndexOf(const QStringRef &str, int from = -1, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

This function overloads lastIndexOf().

Returns the index position of the last occurrence of the string reference str in this string, searching backward from index position from. If from is -1 (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 (default), the search is case sensitive; otherwise the search is case insensitive.

This function was introduced in Qt 4.8.

See also indexOf(), contains(), and count().

int QString::lastIndexOf(const QRegExp &rx, int from = -1) const

This function overloads lastIndexOf().

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

int QString::lastIndexOf(QRegExp &rx, int from = -1) const

This function overloads lastIndexOf().

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.

If there is a match, the rx regular expression will contain the matched captures (see QRegExp::matchedLength, QRegExp::cap).

Example:


  QString str = "the minimum";
  str.lastIndexOf(QRegExp("m[aeiou]"));      // returns 8

This function was introduced in Qt 4.5.

int QString::lastIndexOf(const QRegularExpression &re, int from = -1) const

This function overloads lastIndexOf().

Returns the index position of the last match of the regular expression re in the string, which starts before the index position from. Returns -1 if re didn't match anywhere.

Example:


  QString str = "the minimum";
  str.lastIndexOf(QRegularExpression("m[aeiou]"));      // returns 8

This function was introduced in Qt 5.0.

int QString::lastIndexOf(const QRegularExpression &re, int from, QRegularExpressionMatch *rmatch) const

This is an overloaded function.

Returns the index position of the last match of the regular expression re in the string, which starts before the index position from. Returns -1 if re didn't match anywhere.

If the match is successful and rmatch is not a null pointer, it also writes the results of the match into the QRegularExpressionMatch object pointed to by rmatch.

Example:


  QString str = "the minimum";
  QRegularExpressionMatch match;
  str.lastIndexOf(QRegularExpression("m[aeiou]"), -1, &match);      // returns 8
  // match.captured() == mu

This function was introduced in Qt 5.5.

QString QString::left(int n) const

Returns a substring that contains the n leftmost characters of the string.

The entire string is returned if n is greater than or equal to size(), or less than zero.


  QString x = "Pineapple";
  QString y = x.left(4);      // y == "Pine"

See also right(), mid(), startsWith(), chopped(), chop(), and truncate().

QString QString::leftJustified(int width, QChar fill = QLatin1Char(' '), bool truncate = false) const

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().

QStringRef QString::leftRef(int n) const

Returns a substring reference to the n leftmost characters of the string.

If n is greater than or equal to 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().

int QString::localeAwareCompare(const QString &other) const

This function overloads localeAwareCompare().

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.

The comparison is performed in a locale- and also platform-dependent manner. Use this function to present sorted lists of strings to the user.

Same as localeAwareCompare(*this, other).

QString QString::mid(int position, int n = -1) const

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 (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"

See also left(), right(), chopped(), chop(), and truncate().

QStringRef QString::midRef(int position, int n = -1) const

Returns a substring reference to n characters of this string, starting at the specified position.

If the position exceeds the length of the string, a null reference is returned.

If there are less than n characters available in the string, starting at the given position, or if n is -1 (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().

QString QString::normalized(QString::NormalizationForm mode, QChar::UnicodeVersion version = QChar::Unicode_Unassigned) const

Returns the string in the given Unicode normalization mode, according to the given version of the Unicode standard.

[static] QString QString::number(int n, int base = 10)

This is an overloaded function.

[static] QString QString::number(uint n, int base = 10)

This is an overloaded function.

[static] QString QString::number(qlonglong n, int base = 10)

This is an overloaded function.

[static] QString QString::number(qulonglong n, int base = 10)

This is an overloaded function.

QString &QString::remove(QChar ch, Qt::CaseSensitivity cs = Qt::CaseSensitive)

Removes every occurrence of the character ch in this string, and returns a reference to this string.

If cs is Qt::CaseSensitive (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().

QString &QString::remove(QLatin1String str, Qt::CaseSensitivity cs = Qt::CaseSensitive)

This is an overloaded function.

Removes every occurrence of the given str string in this string, and returns a reference to this string.

If cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.

This is the same as replace(str, "", cs).

This function was introduced in Qt 5.11.

See also replace().

QString &QString::remove(const QString &str, Qt::CaseSensitivity cs = Qt::CaseSensitive)

Removes every occurrence of the given str string in this string, and returns a reference to this string.

If cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.

This is the same as replace(str, "", cs).

See also replace().

QString QString::repeated(int times) const

Returns a copy of this string repeated the specified number of times.

If times is less than 1, an empty string is returned.

Example:


  QString str("ab");
  str.repeated(4);            // returns "abababab"

This function was introduced in Qt 4.5.

QString &QString::replace(QChar before, QChar after, Qt::CaseSensitivity cs = Qt::CaseSensitive)

This function overloads replace().

Replaces every occurrence of the character before with the character after and returns a reference to this string.

If cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.

QString &QString::replace(const QChar *before, int blen, const QChar *after, int alen, Qt::CaseSensitivity cs = Qt::CaseSensitive)

This function overloads replace().

Replaces each occurrence in this string of the first blen characters of before with the first alen characters of after and returns a reference to this string.

If cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.

This function was introduced in Qt 4.5.

QString &QString::replace(QLatin1String before, QLatin1String after, Qt::CaseSensitivity cs = Qt::CaseSensitive)

This function overloads replace().

Replaces every occurrence of the string before with the string after and returns a reference to this string.

If cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.

Note: The text is not rescanned after a replacement.

This function was introduced in Qt 4.5.

QString &QString::replace(QLatin1String before, const QString &after, Qt::CaseSensitivity cs = Qt::CaseSensitive)

This function overloads replace().

Replaces every occurrence of the string before with the string after and returns a reference to this string.

If cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.

Note: The text is not rescanned after a replacement.

This function was introduced in Qt 4.5.

QString &QString::replace(const QString &before, QLatin1String after, Qt::CaseSensitivity cs = Qt::CaseSensitive)

This function overloads replace().

Replaces every occurrence of the string before with the string after and returns a reference to this string.

If cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.

Note: The text is not rescanned after a replacement.

This function was introduced in Qt 4.5.

QString &QString::replace(const QString &before, const QString &after, Qt::CaseSensitivity cs = Qt::CaseSensitive)

This function overloads replace().

Replaces every occurrence of the string before with the string after and returns a reference to this string.

If cs is Qt::CaseSensitive (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"

QString &QString::replace(QChar ch, const QString &after, Qt::CaseSensitivity cs = Qt::CaseSensitive)

This function overloads replace().

Replaces every occurrence of the character ch in the string with after and returns a reference to this string.

If cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.

QString &QString::replace(QChar c, QLatin1String after, Qt::CaseSensitivity cs = Qt::CaseSensitive)

This function overloads replace().

Replaces every occurrence of the character c with the string after and returns a reference to this string.

If cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.

Note: The text is not rescanned after a replacement.

This function was introduced in Qt 4.5.

QString &QString::replace(const QRegExp &rx, const QString &after)

This function overloads replace().

Replaces every occurrence of the regular expression rx in the string with after. Returns a reference to the string. For example:


  QString s = "Banana";
  s.replace(QRegExp("a[mn]"), "ox");
  // s == "Boxoxa"

For regular expressions containing capturing parentheses, occurrences of \1, \2, ..., in after are replaced with rx.cap(1), cap(2), ...


  QString t = "A <i>bon mot</i>.";
  t.replace(QRegExp("<i>([^<]*)</i>"), "\\emph{\\1}");
  // t == "A \\emph{bon mot}."

See also indexOf(), lastIndexOf(), remove(), and QRegExp::cap().

QString &QString::replace(const QRegularExpression &re, const QString &after)

This function overloads replace().

Replaces every occurrence of the regular expression re in the string with after. Returns a reference to the string. For example:


  QString s = "Banana";
  s.replace(QRegularExpression("a[mn]"), "ox");
  // s == "Boxoxa"

For regular expressions containing capturing groups, occurrences of \1, \2, ..., in after are replaced with the string captured by the corresponding capturing group.


  QString t = "A <i>bon mot</i>.";
  t.replace(QRegularExpression("<i>([^<]*)</i>"), "\\emph{\\1}");
  // t == "A \\emph{bon mot}."

This function was introduced in Qt 5.0.

See also indexOf(), lastIndexOf(), remove(), QRegularExpression, and QRegularExpressionMatch.

void QString::resize(int size)

Sets the size of the string to size characters.

If size is greater than the current size, the string is extended to make it size characters long with the extra characters added to the end. The new characters are uninitialized.

If size is less than the current size, characters are removed from the end.

Example:


  QString s = "Hello world";
  s.resize(5);
  // s == "Hello"

  s.resize(8);
  // s == "Hello???" (where ? stands for any character)

If you want to append a certain number of identical characters to the string, use the resize(int, QChar) overload.

If you want to expand the string so that it reaches a certain width and fill the new positions with a particular character, use the leftJustified() function:

If size is negative, it is equivalent to passing zero.


  QString r = "Hello";
  r = r.leftJustified(10, ' ');
  // r == "Hello     "

See also truncate() and reserve().

void QString::resize(int size, QChar fillChar)

This is an overloaded function.

Unlike resize(int), this overload initializes the new characters to fillChar:


  QString t = "Hello";
  r.resize(t.size() + 10, 'X');
  // t == "HelloXXXXXXXXXX"

This function was introduced in Qt 5.7.

Returns a substring that contains the n rightmost characters of the string.

The entire string is returned if n is greater than or equal to size(), or less than zero.


  QString x = "Pineapple";
  QString y = x.right(5);      // y == "apple"

See also left(), mid(), endsWith(), chopped(), chop(), and truncate().

QString QString::rightJustified(int width, QChar fill = QLatin1Char(' '), bool truncate = false) const

Returns a string of size() width that contains the fill character followed by the string. For example:


  QString s = "apple";
  QString t = s.rightJustified(8, '.');    // t == "...apple"

If truncate is false and the size() of the string is more than width, then the returned string is a copy of the string.

If truncate is true and the size() of the string is more than width, then the resulting string is truncated at position width.


  QString str = "Pineapple";
  str = str.rightJustified(5, '.', true);    // str == "Pinea"

See also leftJustified().

QStringRef QString::rightRef(int n) const

Returns a substring reference to the n rightmost characters of the string.

If n is greater than or equal to size(), or less than zero, a reference to the entire string is returned.


  QString x = "Pineapple";
  QStringRef y = x.rightRef(5);       // y == "apple"

This function was introduced in Qt 4.4.

See also right(), leftRef(), midRef(), and endsWith().

QString QString::section(const QString &sep, int start, int end = -1, QString::SectionFlags flags = SectionDefault) const

This function overloads section().


  QString str;
  QString data = "forename**middlename**surname**phone";

  str = data.section("**", 2, 2); // str == "surname"
  str = data.section("**", -3, -2); // str == "middlename**surname"

See also split().

QString QString::section(const QRegExp &reg, int start, int end = -1, QString::SectionFlags flags = SectionDefault) const

This function overloads section().

This string is treated as a sequence of fields separated by the regular expression, reg.


  QString line = "forename\tmiddlename  surname \t \t phone";
  QRegExp sep("\\s+");
  str = line.section(sep, 2, 2); // str == "surname"
  str = line.section(sep, -3, -2); // str == "middlename  surname"

Warning: Using this QRegExp version is much more expensive than the overloaded string and character versions.

See also split() and simplified().

QString QString::section(const QRegularExpression &re, int start, int end = -1, QString::SectionFlags flags = SectionDefault) const

This function overloads section().

This string is treated as a sequence of fields separated by the regular expression, re.


  QString line = "forename\tmiddlename  surname \t \t phone";
  QRegularExpression sep("\\s+");
  str = line.section(sep, 2, 2); // str == "surname"
  str = line.section(sep, -3, -2); // str == "middlename  surname"

Warning: Using this QRegularExpression version is much more expensive than the overloaded string and character versions.

This function was introduced in Qt 5.0.

See also split() and simplified().

QString &QString::setNum(qlonglong n, int base = 10)

This is an overloaded function.

QString &QString::setNum(qulonglong n, int base = 10)

This is an overloaded function.

QString &QString::setRawData(const QChar *unicode, int size)

Resets the QString to use 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.

This function can be used instead of fromRawData() to re-use existings QString objects to save memory re-allocations.

This function was introduced in Qt 4.7.

See also fromRawData().

QString &QString::setUnicode(const QChar *unicode, int size)

Resizes the string to size characters and copies unicode into the string.

If unicode is 0, nothing is copied, but the string is still resized to size.

See also unicode() and setUtf16().

QStringList QString::split(const QString &sep, QString::SplitBehavior behavior = KeepEmptyParts, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

Splits the string into substrings wherever sep occurs, and returns the list of those strings. If sep does not match anywhere in the string, split() returns a single-element list containing this string.

cs specifies whether sep should be matched case sensitively or case insensitively.

If behavior is QString::SkipEmptyParts, empty entries don't appear in the result. By default, empty entries are kept.

Example:


  QString str = "a,,b,c";

  QStringList list1 = str.split(',');
  // list1: [ "a", "", "b", "c" ]

  QStringList list2 = str.split(',', QString::SkipEmptyParts);
  // list2: [ "a", "b", "c" ]

If sep is empty, split() returns an empty string, followed by each of the string's characters, followed by another empty string:


  QString str = "abc";
  auto parts = str.split("");
  // parts: {"", "a", "b", "c", ""}

To understand this behavior, recall that the empty string matches everywhere, so the above is qualitatively the same as:


  QString str = "/a/b/c/";
  auto parts = str.split('/');
  // parts: {"", "a", "b", "c", ""}

See also QStringList::join() and section().

QStringList QString::split(QChar sep, QString::SplitBehavior behavior = KeepEmptyParts, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

This is an overloaded function.

QStringList QString::split(const QRegExp &rx, QString::SplitBehavior behavior = KeepEmptyParts) const

This is an overloaded function.

Splits the string into substrings wherever the regular expression rx matches, and returns the list of those strings. If rx does not match anywhere in the string, split() returns a single-element list containing this string.

Here is an example where we extract the words in a sentence using one or more whitespace characters as the separator:


  QString str;
  QStringList list;

  str = "Some  text\n\twith  strange whitespace.";
  list = str.split(QRegExp("\\s+"));
  // list: [ "Some", "text", "with", "strange", "whitespace." ]

Here is a similar example, but this time we use any sequence of non-word characters as the separator:


  str = "This time, a normal English sentence.";
  list = str.split(QRegExp("\\W+"), QString::SkipEmptyParts);
  // list: [ "This", "time", "a", "normal", "English", "sentence" ]

Here is a third example where we use a zero-length assertion, \b (word boundary), to split the string into an alternating sequence of non-word and word tokens:


  str = "Now: this sentence fragment.";
  list = str.split(QRegExp("\\b"));
  // list: [ "", "Now", ": ", "this", " ", "sentence", " ", "fragment", "." ]

See also QStringList::join() and section().

QStringList QString::split(const QRegularExpression &re, QString::SplitBehavior behavior = KeepEmptyParts) const

This is an overloaded function.

Splits the string into substrings wherever the regular expression re matches, and returns the list of those strings. If re does not match anywhere in the string, split() returns a single-element list containing this string.

Here is an example where we extract the words in a sentence using one or more whitespace characters as the separator:


  QString str;
  QStringList list;

  str = "Some  text\n\twith  strange whitespace.";
  list = str.split(QRegularExpression("\\s+"));
  // list: [ "Some", "text", "with", "strange", "whitespace." ]

Here is a similar example, but this time we use any sequence of non-word characters as the separator:


  str = "This time, a normal English sentence.";
  list = str.split(QRegularExpression("\\W+"), QString::SkipEmptyParts);
  // list: [ "This", "time", "a", "normal", "English", "sentence" ]

Here is a third example where we use a zero-length assertion, \b (word boundary), to split the string into an alternating sequence of non-word and word tokens:


  str = "Now: this sentence fragment.";
  list = str.split(QRegularExpression("\\b"));
  // list: [ "", "Now", ": ", "this", " ", "sentence", " ", "fragment", "." ]

This function was introduced in Qt 5.0.

See also QStringList::join() and section().

QVector<QStringRef> QString::splitRef(const QString &sep, QString::SplitBehavior behavior = KeepEmptyParts, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

Splits the string into substring references wherever sep occurs, and returns the list of those strings.

See QString::split() for how sep, behavior and cs interact to form the result.

Note: All references are valid as long this string is alive. Destroying this string will cause all references to be dangling pointers.

This function was introduced in Qt 5.4.

See also QStringRef and split().

QVector<QStringRef> QString::splitRef(QChar sep, QString::SplitBehavior behavior = KeepEmptyParts, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

This is an overloaded function.

This function was introduced in Qt 5.4.

QVector<QStringRef> QString::splitRef(const QRegExp &rx, QString::SplitBehavior behavior = KeepEmptyParts) const

This is an overloaded function.

Splits the string into substring references wherever the regular expression rx matches, and returns the list of those strings. If rx does not match anywhere in the string, splitRef() returns a single-element vector containing this string reference.

Note: All references are valid as long this string is alive. Destroying this string will cause all references to be dangling pointers.

This function was introduced in Qt 5.4.

See also QStringRef and split().

QVector<QStringRef> QString::splitRef(const QRegularExpression &re, QString::SplitBehavior behavior = KeepEmptyParts) const

This is an overloaded function.

Splits the string into substring references wherever the regular expression re matches, and returns the list of those strings. If re does not match anywhere in the string, splitRef() returns a single-element vector containing this string reference.

Note: All references are valid as long this string is alive. Destroying this string will cause all references to be dangling pointers.

This function was introduced in Qt 5.4.

See also split() and QStringRef.

bool QString::startsWith(const QString &s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

Returns true if the string starts with s; otherwise returns false.

If cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.


  QString str = "Bananas";
  str.startsWith("Ban");     // returns true
  str.startsWith("Car");     // returns false

See also endsWith().

bool QString::startsWith(const QStringRef &s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

This is an overloaded function.

Returns true if the string starts with the string reference s; otherwise returns false.

If cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.

This function was introduced in Qt 4.8.

See also endsWith().

bool QString::startsWith(QLatin1String s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

This function overloads startsWith().

bool QString::startsWith(QChar c, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

This function overloads startsWith().

Returns true if the string starts with c; otherwise returns false.

CFStringRef QString::toCFString() const

Creates a CFString from a QString. The caller owns the CFString and is responsible for releasing it.

Note: this function is only available on OS X and iOS.

This function was introduced in Qt 5.2.

double QString::toDouble(bool *ok = nullptr) const

Returns the string converted to a double value.

Returns an infinity if the conversion overflows or 0.0 if the conversion fails for other reasons (e.g. underflow).

If ok is not nullptr, failure is reported by setting *ok to false, and success by setting *ok to true.


  QString str = "1234.56";
  double val = str.toDouble();   // val == 1234.56

Warning: The QString content may only contain valid numerical characters which includes the plus/minus sign, the character e used in scientific notation, and the decimal point. Including the unit or additional characters leads to a conversion error.


  bool ok;
  double d;

  d = QString( "1234.56e-02" ).toDouble(&ok); // ok == true, d == 12.3456

  d = QString( "1234.56e-02 Volt" ).toDouble(&ok); // ok == false, d == 0

The string conversion will always happen in the 'C' locale. For locale dependent conversion use QLocale::toDouble()


  d = QString( "1234,56" ).toDouble(&ok); // ok == false
  d = QString( "1234.56" ).toDouble(&ok); // ok == true, d == 1234.56

For historical reasons, this function does not handle thousands group separators. If you need to convert such numbers, use QLocale::toDouble().


  d = QString( "1,234,567.89" ).toDouble(&ok); // ok == false
  d = QString( "1234567.89" ).toDouble(&ok); // ok == true

This function ignores leading and trailing whitespace.

See also number(), QLocale::setDefault(), QLocale::toDouble(), and trimmed().

float QString::toFloat(bool *ok = nullptr) const

Returns the string converted to a float value.

Returns an infinity if the conversion overflows or 0.0 if the conversion fails for other reasons (e.g. underflow).

If ok is not nullptr, failure is reported by setting *ok to false, and success by setting *ok to true.

Warning: The QString content may only contain valid numerical characters which includes the plus/minus sign, the character e used in scientific notation, and the decimal point. Including the unit or additional characters leads to a conversion error.

The string conversion will always happen in the 'C' locale. For locale dependent conversion use QLocale::toFloat()

For historical reasons, this function does not handle thousands group separators. If you need to convert such numbers, use QLocale::toFloat().

Example:


  QString str1 = "1234.56";
  str1.toFloat();             // returns 1234.56

  bool ok;
  QString str2 = "R2D2";
  str2.toFloat(&ok);          // returns 0.0, sets ok to false

  QString str3 = "1234.56 Volt";
  str3.toFloat(&ok);          // returns 0.0, sets ok to false

This function ignores leading and trailing whitespace.

See also number(), toDouble(), toInt(), QLocale::toFloat(), and trimmed().

QString QString::toHtmlEscaped() const

Converts a plain text string to an HTML string with HTML metacharacters <, >, &, and " replaced by HTML entities.

Example:


  QString plain = "#include <QtCore>"
  QString html = plain.toHtmlEscaped();
  // html == "#include &lt;QtCore&gt;"

This function was introduced in Qt 5.0.

int QString::toInt(bool *ok = nullptr, int base = 10) const

Returns the string converted to an int using base base, which is 10 by default and must be between 2 and 36, or 0. Returns 0 if the conversion fails.

If ok is not nullptr, failure is reported by setting *ok to false, and success by setting *ok to true.

If base is 0, the C language convention is used: If the string begins with "0x", base 16 is used; if the string begins with "0", base 8 is used; otherwise, base 10 is used.

The string conversion will always happen in the 'C' locale. For locale dependent conversion use QLocale::toInt()

Example:


  QString str = "FF";
  bool ok;
  int hex = str.toInt(&ok, 16);       // hex == 255, ok == true
  int dec = str.toInt(&ok, 10);       // dec == 0, ok == false

This function ignores leading and trailing whitespace.

See also number(), toUInt(), toDouble(), and QLocale::toInt().

qlonglong QString::toLongLong(bool *ok = nullptr, int base = 10) const

Returns the string converted to a long long using base base, which is 10 by default and must be between 2 and 36, or 0. Returns 0 if the conversion fails.

If ok is not nullptr, failure is reported by setting *ok to false, and success by setting *ok to true.

If base is 0, the C language convention is used: If the string begins with "0x", base 16 is used; if the string begins with "0", base 8 is used; otherwise, base 10 is used.

The string conversion will always happen in the 'C' locale. For locale dependent conversion use QLocale::toLongLong()

Example:


  QString str = "FF";
  bool ok;

  qint64 hex = str.toLongLong(&ok, 16);      // hex == 255, ok == true
  qint64 dec = str.toLongLong(&ok, 10);      // dec == 0, ok == false

This function ignores leading and trailing whitespace.

See also number(), toULongLong(), toInt(), and QLocale::toLongLong().

NSString *QString::toNSString() const

Creates a NSString from a QString. The NSString is autoreleased.

Note: this function is only available on OS X and iOS.

This function was introduced in Qt 5.2.

short QString::toShort(bool *ok = nullptr, int base = 10) const

Returns the string converted to a short using base base, which is 10 by default and must be between 2 and 36, or 0. Returns 0 if the conversion fails.

If ok is not nullptr, failure is reported by setting *ok to false, and success by setting *ok to true.

If base is 0, the C language convention is used: If the string begins with "0x", base 16 is used; if the string begins with "0", base 8 is used; otherwise, base 10 is used.

The string conversion will always happen in the 'C' locale. For locale dependent conversion use QLocale::toShort()

Example:


  QString str = "FF";
  bool ok;

  short hex = str.toShort(&ok, 16);   // hex == 255, ok == true
  short dec = str.toShort(&ok, 10);   // dec == 0, ok == false

This function ignores leading and trailing whitespace.

See also number(), toUShort(), toInt(), and QLocale::toShort().

uint QString::toUInt(bool *ok = nullptr, int base = 10) const

Returns the string converted to an unsigned int using base base, which is 10 by default and must be between 2 and 36, or 0. Returns 0 if the conversion fails.

If ok is not nullptr, failure is reported by setting *ok to false, and success by setting *ok to true.

If base is 0, the C language convention is used: If the string begins with "0x", base 16 is used; if the string begins with "0", base 8 is used; otherwise, base 10 is used.

The string conversion will always happen in the 'C' locale. For locale dependent conversion use QLocale::toUInt()

Example:


  QString str = "FF";
  bool ok;

  uint hex = str.toUInt(&ok, 16);     // hex == 255, ok == true
  uint dec = str.toUInt(&ok, 10);     // dec == 0, ok == false

This function ignores leading and trailing whitespace.

See also number(), toInt(), and QLocale::toUInt().

qulonglong QString::toULongLong(bool *ok = nullptr, int base = 10) const

Returns the string converted to an unsigned long long using base base, which is 10 by default and must be between 2 and 36, or 0. Returns 0 if the conversion fails.

If ok is not nullptr, failure is reported by setting *ok to false, and success by setting *ok to true.

If base is 0, the C language convention is used: If the string begins with "0x", base 16 is used; if the string begins with "0", base 8 is used; otherwise, base 10 is used.

The string conversion will always happen in the 'C' locale. For locale dependent conversion use QLocale::toULongLong()

Example:


  QString str = "FF";
  bool ok;

  quint64 hex = str.toULongLong(&ok, 16);    // hex == 255, ok == true
  quint64 dec = str.toULongLong(&ok, 10);    // dec == 0, ok == false

This function ignores leading and trailing whitespace.

See also number(), toLongLong(), and QLocale::toULongLong().

ushort QString::toUShort(bool *ok = nullptr, int base = 10) const

Returns the string converted to an unsigned short using base base, which is 10 by default and must be between 2 and 36, or 0. Returns 0 if the conversion fails.

If ok is not nullptr, failure is reported by setting *ok to false, and success by setting *ok to true.

If base is 0, the C language convention is used: If the string begins with "0x", base 16 is used; if the string begins with "0", base 8 is used; otherwise, base 10 is used.

The string conversion will always happen in the 'C' locale. For locale dependent conversion use QLocale::toUShort()

Example:


  QString str = "FF";
  bool ok;

  ushort hex = str.toUShort(&ok, 16);     // hex == 255, ok == true
  ushort dec = str.toUShort(&ok, 10);     // dec == 0, ok == false

This function ignores leading and trailing whitespace.

See also number(), toShort(), and QLocale::toUShort().

QVector<uint> QString::toUcs4() const

Returns a UCS-4/UTF-32 representation of the string as a QVector<uint>.

UCS-4 is a Unicode codec and therefore it is lossless. All characters from this string will be encoded in UCS-4. Any invalid sequence of code units in this string is replaced by the Unicode's replacement character (QChar::ReplacementCharacter, which corresponds to U+FFFD).

The returned vector is not NUL terminated.

This function was introduced in Qt 4.2.

See also fromUtf8(), toUtf8(), toLatin1(), toLocal8Bit(), QTextCodec, fromUcs4(), and toWCharArray().

bool QString::operator<(QLatin1String other) const

This function overloads operator<().

Returns true if this string is lexically less than the parameter string called other; otherwise returns false.

QString &QString::operator=(QChar ch)

This function overloads operator=().

Sets the string to contain the single character ch.

bool QString::operator==(QLatin1String other) const

This function overloads operator==().

Returns true if this string is equal to other; otherwise returns false.

bool QString::operator>(QLatin1String other) const

This function overloads operator>().

Returns true if this string is lexically greater than the parameter string other; otherwise returns false.

Related Non-Members

bool QString::operator!=(const int &s1, const int &s2)

Returns true if s1 and s2 are different; otherwise returns false.

This function was introduced in Qt 5.0.

bool QString::operator<(const QString &s1, const QString &s2)

Returns true if string s1 is lexically less than string s2; otherwise returns false.

The 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-interface strings using the QString::localeAwareCompare() function.

bool QString::operator==(const QString &s1, const QString &s2)

Returns true if string s1 is equal to string s2; otherwise returns false.

The 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-interface strings with localeAwareCompare().

Macro Documentation

QString::QStringLiteral(str)

The macro generates the data for a QString out of the string literal str at compile time. Creating a QString from it is free in this case, and the generated string data is stored in the read-only segment of the compiled object file.

If you have code that looks like this:


  // hasAttribute takes a QString argument
  if (node.hasAttribute("http-contents-length")) //...

then a temporary QString will be created to be passed as the hasAttribute function parameter. This can be quite expensive, as it involves a memory allocation and the copy/conversion of the data into QString's internal encoding.

This cost can be avoided by using QStringLiteral instead:


  if (node.hasAttribute(QStringLiteral(u"http-contents-length"))) //...

In this case, QString's internal data will be generated at compile time; no conversion or allocation will occur at runtime.

Using QStringLiteral instead of a double quoted plain C++ string literal can significantly speed up creation of QString instances from data known at compile time.

Note: QLatin1String can still be more efficient than QStringLiteral when the string is passed to a function that has an overload taking QLatin1String and this overload avoids conversion to QString. For instance, QString::operator==() can compare to a QLatin1String directly:


  if (attribute.name() == QLatin1String("http-contents-length")) //...

Note: Some compilers have bugs encoding strings containing characters outside the US-ASCII character set. Make sure you prefix your string with u in those cases. It is optional otherwise.

See also QByteArrayLiteral.

QString::QT_NO_CAST_FROM_ASCII

Disables automatic conversions from 8-bit strings (char *) to unicode QStrings

See also QT_NO_CAST_TO_ASCII, QT_RESTRICTED_CAST_FROM_ASCII, and QT_NO_CAST_FROM_BYTEARRAY.

QString::QT_NO_CAST_TO_ASCII

disables automatic conversion from QString to 8-bit strings (char *)

See also QT_NO_CAST_FROM_ASCII, QT_RESTRICTED_CAST_FROM_ASCII, and QT_NO_CAST_FROM_BYTEARRAY.

QString::QT_RESTRICTED_CAST_FROM_ASCII

Defining this macro disables most automatic conversions from source literals and 8-bit data to unicode QStrings, but allows the use of the QChar(char) and QString(const char (&ch)[N] constructors, and the QString::operator=(const char (&ch)[N]) assignment operator giving most of the type-safety benefits of QT_NO_CAST_FROM_ASCII but does not require user code to wrap character and string literals with QLatin1Char, QLatin1String or similar.

Using this macro together with source strings outside the 7-bit range, non-literals, or literals with embedded NUL characters is undefined.

See also QT_NO_CAST_FROM_ASCII and QT_NO_CAST_TO_ASCII.