QString Class

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

Header: #include <QString>
CMake: find_package(Qt6 REQUIRED COMPONENTS Core)
target_link_libraries(mytarget PRIVATE Qt6::Core)
qmake: QT += core

This class is strongly comparable.

This class is strongly comparable with QChar, QLatin1StringView, const char16_t *, QStringView, and QUtf8StringView.

This class is strongly comparable with QByteArray, QByteArrayView, and const char *.

When comparing with byte arrays, their content is interpreted as utf-8.

Note: All functions in this class are reentrant.

Public Types

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

Public Functions

QString()
QString(QChar ch)
QString(QLatin1StringView str)
QString(const QByteArray &ba)
QString(const char *str)
(since 6.1) QString(const char8_t *str)
QString(const QChar *unicode, qsizetype size = -1)
QString(qsizetype size, QChar ch)
QString(const QString &other)
QString(QString &&other)
~QString()
QString &append(const QString &str)
QString &append(QChar ch)
QString &append(QLatin1StringView str)
(since 6.0) QString &append(QStringView v)
(since 6.5) QString &append(QUtf8StringView str)
QString &append(const QByteArray &ba)
QString &append(const char *str)
QString &append(const QChar *str, qsizetype len)
QString arg(Args &&... args) const
QString arg(const QString &a, int fieldWidth = 0, QChar fillChar = u' ') const
QString arg(QChar a, int fieldWidth = 0, QChar fillChar = u' ') const
QString arg(QLatin1StringView a, int fieldWidth = 0, QChar fillChar = u' ') const
QString arg(QStringView a, int fieldWidth = 0, QChar fillChar = u' ') const
QString arg(char a, int fieldWidth = 0, QChar fillChar = u' ') const
QString arg(int a, int fieldWidth = 0, int base = 10, QChar fillChar = u' ') const
QString arg(long a, int fieldWidth = 0, int base = 10, QChar fillChar = u' ') const
QString arg(qlonglong a, int fieldWidth = 0, int base = 10, QChar fillChar = u' ') const
QString arg(qulonglong a, int fieldWidth = 0, int base = 10, QChar fillChar = u' ') const
QString arg(short a, int fieldWidth = 0, int base = 10, QChar fillChar = u' ') const
QString arg(uint a, int fieldWidth = 0, int base = 10, QChar fillChar = u' ') const
QString arg(ulong a, int fieldWidth = 0, int base = 10, QChar fillChar = u' ') const
QString arg(ushort a, int fieldWidth = 0, int base = 10, QChar fillChar = u' ') const
QString arg(double a, int fieldWidth = 0, char format = 'g', int precision = -1, QChar fillChar = u' ') const
(since 6.6) QString &assign(QAnyStringView v)
(since 6.6) QString &assign(InputIterator first, InputIterator last)
(since 6.6) QString &assign(qsizetype n, QChar c)
const QChar at(qsizetype position) const
QChar &back()
QChar back() const
QString::iterator begin()
QString::const_iterator begin() const
qsizetype capacity() const
QString::const_iterator cbegin() const
QString::const_iterator cend() const
void chop(qsizetype n)
QString chopped(qsizetype len) &&
QString chopped(qsizetype len) const &
void clear()
int compare(QChar ch, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
int compare(QLatin1StringView other, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
int compare(QStringView s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
int compare(const QString &other, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
QString::const_iterator constBegin() const
const QChar *constData() const
QString::const_iterator constEnd() const
bool contains(const QRegularExpression &re, QRegularExpressionMatch *rmatch = nullptr) const
bool contains(const QString &str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
bool contains(QChar ch, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
bool contains(QLatin1StringView str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
bool contains(QStringView str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
qsizetype count(const QString &str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
qsizetype count(const QRegularExpression &re) const
qsizetype count(QChar ch, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
(since 6.0) qsizetype count(QStringView str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
QString::const_reverse_iterator crbegin() const
QString::const_reverse_iterator crend() const
QChar *data()
const QChar *data() const
QString::iterator end()
QString::const_iterator end() const
bool endsWith(const QString &s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
bool endsWith(QChar c, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
bool endsWith(QLatin1StringView s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
bool endsWith(QStringView str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
(since 6.1) QString::iterator erase(QString::const_iterator first, QString::const_iterator last)
(since 6.5) QString::iterator erase(QString::const_iterator it)
QString &fill(QChar ch, qsizetype size = -1)
(since 6.0) QString first(qsizetype n) &&
(since 6.0) QString first(qsizetype n) const &
QChar &front()
QChar front() const
qsizetype indexOf(QLatin1StringView str, qsizetype from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
qsizetype indexOf(const QRegularExpression &re, qsizetype from = 0, QRegularExpressionMatch *rmatch = nullptr) const
qsizetype indexOf(const QString &str, qsizetype from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
qsizetype indexOf(QChar ch, qsizetype from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
qsizetype indexOf(QStringView str, qsizetype from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
QString &insert(qsizetype position, const QString &str)
QString &insert(qsizetype position, QChar ch)
QString &insert(qsizetype position, QLatin1StringView str)
(since 6.0) QString &insert(qsizetype position, QStringView str)
(since 6.5) QString &insert(qsizetype position, QUtf8StringView str)
QString &insert(qsizetype position, const QByteArray &str)
QString &insert(qsizetype position, const char *str)
QString &insert(qsizetype position, const QChar *unicode, qsizetype size)
bool isEmpty() const
bool isLower() const
bool isNull() const
bool isRightToLeft() const
bool isUpper() const
bool isValidUtf16() const
(since 6.0) QString last(qsizetype n) &&
(since 6.0) QString last(qsizetype n) const &
qsizetype lastIndexOf(const QRegularExpression &re, qsizetype from, QRegularExpressionMatch *rmatch = nullptr) const
qsizetype lastIndexOf(const QString &str, qsizetype from, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
(since 6.3) qsizetype lastIndexOf(QChar ch, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
(since 6.2) qsizetype lastIndexOf(QLatin1StringView str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
(since 6.2) qsizetype lastIndexOf(QStringView str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
(since 6.2) qsizetype lastIndexOf(const QRegularExpression &re, QRegularExpressionMatch *rmatch = nullptr) const
(since 6.2) qsizetype lastIndexOf(const QString &str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
qsizetype lastIndexOf(QChar ch, qsizetype from, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
qsizetype lastIndexOf(QLatin1StringView str, qsizetype from, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
qsizetype lastIndexOf(QStringView str, qsizetype from, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
QString left(qsizetype n) &&
QString left(qsizetype n) const &
QString leftJustified(qsizetype width, QChar fill = u' ', bool truncate = false) const
qsizetype length() const
(since 6.0) int localeAwareCompare(QStringView other) const
int localeAwareCompare(const QString &other) const
(since 6.8) qsizetype max_size() const
QString mid(qsizetype position, qsizetype n = -1) &&
QString mid(qsizetype position, qsizetype n = -1) const &
QString normalized(QString::NormalizationForm mode, QChar::UnicodeVersion version = QChar::Unicode_Unassigned) const
QString &prepend(const QString &str)
QString &prepend(QChar ch)
QString &prepend(QLatin1StringView str)
(since 6.0) QString &prepend(QStringView str)
(since 6.5) QString &prepend(QUtf8StringView str)
QString &prepend(const QByteArray &ba)
QString &prepend(const char *str)
QString &prepend(const QChar *str, qsizetype len)
void push_back(const QString &other)
void push_back(QChar ch)
void push_front(const QString &other)
void push_front(QChar ch)
QString::reverse_iterator rbegin()
QString::const_reverse_iterator rbegin() const
QString &remove(const QRegularExpression &re)
QString &remove(QChar ch, Qt::CaseSensitivity cs = Qt::CaseSensitive)
QString &remove(const QString &str, Qt::CaseSensitivity cs = Qt::CaseSensitive)
QString &remove(qsizetype position, qsizetype n)
QString &remove(QLatin1StringView str, Qt::CaseSensitivity cs = Qt::CaseSensitive)
(since 6.5) QString &removeAt(qsizetype pos)
(since 6.5) QString &removeFirst()
(since 6.1) QString &removeIf(Predicate pred)
(since 6.5) QString &removeLast()
QString::reverse_iterator rend()
QString::const_reverse_iterator rend() const
QString repeated(qsizetype times) const
QString &replace(qsizetype position, qsizetype n, const QString &after)
QString &replace(const QRegularExpression &re, const QString &after)
QString &replace(QChar before, QChar after, Qt::CaseSensitivity cs = Qt::CaseSensitive)
QString &replace(QChar c, QLatin1StringView after, Qt::CaseSensitivity cs = Qt::CaseSensitive)
QString &replace(QChar ch, const QString &after, Qt::CaseSensitivity cs = Qt::CaseSensitive)
QString &replace(QLatin1StringView before, QLatin1StringView after, Qt::CaseSensitivity cs = Qt::CaseSensitive)
QString &replace(QLatin1StringView before, const QString &after, Qt::CaseSensitivity cs = Qt::CaseSensitive)
QString &replace(const QString &before, QLatin1StringView after, Qt::CaseSensitivity cs = Qt::CaseSensitive)
QString &replace(const QString &before, const QString &after, Qt::CaseSensitivity cs = Qt::CaseSensitive)
QString &replace(qsizetype position, qsizetype n, QChar after)
QString &replace(qsizetype position, qsizetype n, const QChar *after, qsizetype alen)
QString &replace(const QChar *before, qsizetype blen, const QChar *after, qsizetype alen, Qt::CaseSensitivity cs = Qt::CaseSensitive)
void reserve(qsizetype size)
void resize(qsizetype size)
void resize(qsizetype newSize, QChar fillChar)
(since 6.8) void resizeForOverwrite(qsizetype size)
QString right(qsizetype n) &&
QString right(qsizetype n) const &
QString rightJustified(qsizetype width, QChar fill = u' ', bool truncate = false) const
QString section(QChar sep, qsizetype start, qsizetype end = -1, QString::SectionFlags flags = SectionDefault) const
QString section(const QRegularExpression &re, qsizetype start, qsizetype end = -1, QString::SectionFlags flags = SectionDefault) const
QString section(const QString &sep, qsizetype start, qsizetype end = -1, QString::SectionFlags flags = SectionDefault) const
QString &setNum(int n, int base = 10)
QString &setNum(long n, int base = 10)
QString &setNum(qlonglong n, int base = 10)
QString &setNum(qulonglong n, int base = 10)
QString &setNum(short n, int base = 10)
QString &setNum(uint n, int base = 10)
QString &setNum(ulong n, int base = 10)
QString &setNum(ushort n, int base = 10)
QString &setNum(double n, char format = 'g', int precision = 6)
QString &setNum(float n, char format = 'g', int precision = 6)
QString &setRawData(const QChar *unicode, qsizetype size)
QString &setUnicode(const QChar *unicode, qsizetype size)
QString &setUtf16(const ushort *unicode, qsizetype size)
void shrink_to_fit()
QString simplified() const
qsizetype size() const
(since 6.8) QString &slice(qsizetype pos, qsizetype n)
(since 6.8) QString &slice(qsizetype pos)
(since 6.0) QString sliced(qsizetype pos, qsizetype n) &&
(since 6.0) QString sliced(qsizetype pos, qsizetype n) const &
(since 6.0) QString sliced(qsizetype pos) &&
(since 6.0) QString sliced(qsizetype pos) const &
QStringList split(const QString &sep, Qt::SplitBehavior behavior = Qt::KeepEmptyParts, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
QStringList split(const QRegularExpression &re, Qt::SplitBehavior behavior = Qt::KeepEmptyParts) const
QStringList split(QChar sep, Qt::SplitBehavior behavior = Qt::KeepEmptyParts, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
void squeeze()
bool startsWith(const QString &s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
bool startsWith(QChar c, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
bool startsWith(QLatin1StringView s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
bool startsWith(QStringView str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
void swap(QString &other)
CFStringRef toCFString() const
QString toCaseFolded() const
double toDouble(bool *ok = nullptr) const
(since 6.6) emscripten::val toEcmaString() const
float toFloat(bool *ok = nullptr) const
QString toHtmlEscaped() const
int toInt(bool *ok = nullptr, int base = 10) const
QByteArray toLatin1() const
QByteArray toLocal8Bit() const
long toLong(bool *ok = nullptr, int base = 10) const
qlonglong toLongLong(bool *ok = nullptr, int base = 10) const
QString toLower() const
NSString *toNSString() const
short toShort(bool *ok = nullptr, int base = 10) const
std::string toStdString() const
std::u16string toStdU16String() const
std::u32string toStdU32String() const
std::wstring toStdWString() const
uint toUInt(bool *ok = nullptr, int base = 10) const
ulong toULong(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
QList<uint> toUcs4() const
QString toUpper() const
QByteArray toUtf8() const
qsizetype toWCharArray(wchar_t *array) const
(since 6.0) auto tokenize(Needle &&sep, Flags... flags) &&
(since 6.0) auto tokenize(Needle &&sep, Flags... flags) const &&
(since 6.0) auto tokenize(Needle &&sep, Flags... flags) const &
QString trimmed() const
void truncate(qsizetype position)
const QChar *unicode() const
const ushort *utf16() const
(since 6.7) std::u16string_view operator std::u16string_view() const
QString &operator+=(const QString &other)
QString &operator+=(QChar ch)
QString &operator+=(QLatin1StringView str)
(since 6.0) QString &operator+=(QStringView str)
(since 6.5) QString &operator+=(QUtf8StringView str)
QString &operator+=(const QByteArray &ba)
QString &operator+=(const char *str)
QString &operator=(QString &&other)
QString &operator=(const QString &other)
QString &operator=(QChar ch)
QString &operator=(QLatin1StringView str)
QString &operator=(const QByteArray &ba)
QString &operator=(const char *str)
QChar &operator[](qsizetype position)
const QChar operator[](qsizetype position) const

Static Public Members

QString asprintf(const char *cformat, ...)
int compare(const QString &s1, const QString &s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
int compare(QLatin1StringView s1, const QString &s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
int compare(QStringView s1, const QString &s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
int compare(const QString &s1, QLatin1StringView s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
int compare(const QString &s1, QStringView s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
QString fromCFString(CFStringRef string)
(since 6.6) QString fromEcmaString(emscripten::val jsString)
QString fromLatin1(const char *str, qsizetype size)
(since 6.0) QString fromLatin1(QByteArrayView str)
QString fromLatin1(const QByteArray &str)
QString fromLocal8Bit(const char *str, qsizetype size)
(since 6.0) QString fromLocal8Bit(QByteArrayView str)
QString fromLocal8Bit(const QByteArray &str)
QString fromNSString(const NSString *string)
QString fromRawData(const QChar *unicode, qsizetype size)
QString fromStdString(const std::string &str)
QString fromStdU16String(const std::u16string &str)
QString fromStdU32String(const std::u32string &str)
QString fromStdWString(const std::wstring &str)
QString fromUcs4(const char32_t *unicode, qsizetype size = -1)
QString fromUtf8(const char *str, qsizetype size)
(since 6.0) QString fromUtf8(QByteArrayView str)
QString fromUtf8(const QByteArray &str)
(since 6.1) QString fromUtf8(const char8_t *str)
(since 6.0) QString fromUtf8(const char8_t *str, qsizetype size)
QString fromUtf16(const char16_t *unicode, qsizetype size = -1)
QString fromWCharArray(const wchar_t *string, qsizetype size = -1)
int localeAwareCompare(const QString &s1, const QString &s2)
(since 6.0) int localeAwareCompare(QStringView s1, QStringView s2)
(since 6.8) qsizetype maxSize()
QString number(long n, int base = 10)
QString number(double n, char format = 'g', int precision = 6)
QString number(int n, int base = 10)
QString number(qlonglong n, int base = 10)
QString number(qulonglong n, int base = 10)
QString number(uint n, int base = 10)
QString number(ulong n, int base = 10)
QString vasprintf(const char *cformat, va_list ap)
(since 6.1) qsizetype erase(QString &s, const T &t)
(since 6.1) qsizetype erase_if(QString &s, Predicate pred)
bool operator!=(const QByteArray &lhs, const QString &rhs)
bool operator!=(const QString &lhs, const QString &rhs)
bool operator!=(const char *const &lhs, const QString &rhs)
bool operator!=(const QString &lhs, const QByteArray &rhs)
bool operator!=(const QString &lhs, const QLatin1StringView &rhs)
bool operator!=(const QString &lhs, const char *const &rhs)
QString operator+(QString &&s1, const QString &s2)
QString operator+(const QString &s1, const QString &s2)
QString operator+(const QString &s1, const char *s2)
QString operator+(const char *s1, const QString &s2)
bool operator<(const QByteArray &lhs, const QString &rhs)
bool operator<(const char *const &lhs, const QString &rhs)
bool operator<(const QLatin1StringView &lhs, const QString &rhs)
bool operator<(const QString &lhs, const QByteArray &rhs)
bool operator<(const QString &lhs, const QLatin1StringView &rhs)
bool operator<(const QString &lhs, const QString &rhs)
bool operator<(const QString &lhs, const char *const &rhs)
QDataStream &operator<<(QDataStream &stream, const QString &string)
bool operator<=(const QByteArray &lhs, const QString &rhs)
bool operator<=(const QString &lhs, const QString &rhs)
bool operator<=(const char *const &lhs, const QString &rhs)
bool operator<=(const QLatin1StringView &lhs, const QString &rhs)
bool operator<=(const QString &lhs, const QByteArray &rhs)
bool operator<=(const QString &lhs, const QLatin1StringView &rhs)
bool operator<=(const QString &lhs, const char *const &rhs)
bool operator==(const QByteArray &lhs, const QString &rhs)
bool operator==(const QLatin1StringView &lhs, const QString &rhs)
bool operator==(const QString &lhs, const QByteArray &rhs)
bool operator==(const QString &lhs, const QLatin1StringView &rhs)
bool operator==(const QString &lhs, const QString &rhs)
bool operator==(const QString &lhs, const char *const &rhs)
bool operator==(const char *const &lhs, const QString &rhs)
bool operator>(const QByteArray &lhs, const QString &rhs)
bool operator>(const QString &lhs, const QString &rhs)
bool operator>(const char *const &lhs, const QString &rhs)
bool operator>(const QLatin1StringView &lhs, const QString &rhs)
bool operator>(const QString &lhs, const QByteArray &rhs)
bool operator>(const QString &lhs, const QLatin1StringView &rhs)
bool operator>(const QString &lhs, const char *const &rhs)
bool operator>=(const QByteArray &lhs, const QString &rhs)
bool operator>=(const QString &lhs, const QString &rhs)
bool operator>=(const char *const &lhs, const QString &rhs)
bool operator>=(const QLatin1StringView &lhs, const QString &rhs)
bool operator>=(const QString &lhs, const QByteArray &rhs)
bool operator>=(const QString &lhs, const QLatin1StringView &rhs)
bool operator>=(const QString &lhs, const char *const &rhs)
QDataStream &operator>>(QDataStream &stream, QString &string)

Macros

QStringLiteral(str)
QT_NO_CAST_FROM_ASCII
QT_NO_CAST_TO_ASCII
QT_RESTRICTED_CAST_FROM_ASCII
const char *qPrintable(const QString &str)
const wchar_t *qUtf16Printable(const QString &str)
const char *qUtf8Printable(const QString &str)

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, that is, 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 are easy to translate if you want to expand your application's market at some point. Two prominent 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 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. Except where the function's name overtly indicates some other encoding, such const char * parameters are assumed to be encoded in UTF-8.

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. You can avoid taking a deep copy of the character data by using QStringView or 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 (qsizetype 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 first(), last(), or sliced() 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"

In the above example, the replace() function's first two arguments are the position from which to start replacing and the number of characters that should be replaced.

When data-modifying functions increase the size of the string, QString may reallocate the memory in which it holds its data. When this happens, QString expands by more than it immediately needs so as to have space for further expansion without reallocation until the size of the string has significantly increased.

The insert(), remove(), and, when replacing a sub-string with one of different size, replace() functions can be slow (linear time) for large strings because they require moving many characters in the string by at least one position in memory.

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 the QString actually has allocated.

QString provides STL-style iterators (QString::const_iterator and QString::iterator). In practice, iterators are handy when working with generic algorithms provided by the C++ standard library.

Note: Iterators over a QString, and references to individual characters within one, cannot be relied on to remain valid when any non-const method of the QString is called. Accessing such an iterator or reference after the call to a non-const method leads to undefined behavior. When stability for iterator-like functionality is required, you should use indexes instead of iterators, as they are not tied to QString's internal state and thus do not get invalidated.

Note: Due to implicit sharing, the first non-const operator or function used on a given QString may cause it to internally perform a deep copy of its data. This invalidates all iterators over the string and references to individual characters within it. Do not call non-const functions while keeping iterators. Accessing an iterator or reference after it has been invalidated leads to undefined behavior. See the Implicit sharing iterator problem section for more information.

A frequent requirement is to remove or simplify the spacing between visible characters in a string. The characters that make up that spacing are those for which isSpace() returns true, such as the simple space ' ', the horizontal tab '\\t' and the newline '\\n'. To obtain a copy of a string leaving out any spacing from its start and end, use trimmed(). To also replace each sequence of spacing characters within the string with a simple space, ' ', 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, the latter searches backward. Either can be told an index position from which to start their search. Each returns 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>";
 qsizetype 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 uppercase 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 filtered list from a string list by selecting the entries in it that contain a particular substring or match a particular QRegularExpression. See QStringList::filter() for details.

Querying string data

To see if a QString starts or ends with a particular substring, use startsWith() or endsWith(). To check whether a QString contains a specific character or substring, use the contains() function. To find out how many times a particular character or substring occurs in a string, use count().

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.

Comparing strings

QStrings can be compared using overloaded operators such as operator<(), operator<=(), operator==(), operator>=(), and so on. The comparison is based exclusively on the lexicographical order of the two strings, seen as sequences of UTF-16 code units. It is very fast but is not what a human would expect; the QString::localeAwareCompare() function is usually a better choice for sorting user-interface strings, when such a comparison is available.

When Qt is linked with the ICU library (which it usually is), its locale-aware sorting is used. Otherwise, platform-specific solutions are used:

  • On Windows, localeAwareCompare() uses the current user locale, as set in the regional and language options portion of Control Panel.
  • On macOS and iOS, localeAwareCompare() compares according to the Order for sorted lists setting in the International preferences panel.
  • On other Unix-like systems, the comparison falls back to the system library's strcoll().

Converting between encoded string data and QString

QString provides the following 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. This is the same as toUtf8() on Unix systems.

To convert from one of these encodings, QString provides fromLatin1(), fromUtf8(), and fromLocal8Bit(). Other encodings are supported through the QStringEncoder and QStringDecoder classes.

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 some of the following 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.

You then need to explicitly call fromUtf8(), fromLatin1(), or fromLocal8Bit() to construct a QString from an 8-bit string, or use the lightweight QLatin1StringView class. For example:

 QString url = "https://www.unicode.org/"_L1;

Similarly, you must call toLatin1(), toUtf8(), or toLocal8Bit() explicitly to convert the QString to an 8-bit string.

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 null and empty strings. A null string is a string that is initialized using QString's default constructor or by passing nullptr 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 valid pointer (not nullptr) to a '\0' character for a null string. We recommend that you always use the isEmpty() function and avoid isNull().

Number formats

When a QString::arg() '%' format specifier includes the 'L' locale qualifier, and the base is ten (its default), the default locale is used. This can be set using QLocale::setDefault(). For more refined control of localized string representations of numbers, see QLocale::toString(). All other number formatting done by QString follows the C locale's representation of numbers.

When QString::arg() applies left-padding to numbers, the fill character '0' is treated specially. If the number is negative, its minus sign appears before the zero-padding. If the field is localized, the locale-appropriate zero character is used in place of '0'. For floating-point numbers, this special treatment only applies if the number is finite.

Floating-point formats

In member functions (for example, arg() and number()) that format floating-point numbers (float or double) as strings, the representation used can be controlled by a choice of format and precision, whose meanings are as for QLocale::toString(double, char, int).

If the selected format includes an exponent, localized forms follow the locale's convention on digits in the exponent. For non-localized formatting, the exponent shows its sign and includes at least two digits, left-padding with zero if needed.

More efficient string construction

Many strings are known at compile time. The QString constructor from C++ string literals will copy the contents of the string, treating the contents as UTF-8. This requires memory allocation and re-encoding string data, operations that will happen at runtime. If the string data is known at compile time, you can use the QStringLiteral macro or similarly operator""_s to create QString's payload at compile time instead.

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 = "vector<"_L1 + type + ">::iterator"_L1;

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

There is nothing wrong with either of these string constructions, but there are a few hidden inefficiencies:

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

These allocations can be optimized by an internal class QStringBuilder. 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 reducing reference counting (the QString created from a QStringBuilder 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");
     QStringView el = QStringView{ hello }.mid(2, 3);
     QLatin1StringView world("world");
     QString message =  hello % el % world % QChar('!');

A more global approach, which is more convenient but not entirely source-compatible, is to define QT_USE_QSTRINGBUILDER (by adding it to the compiler flags) at build time. This will make concatenating strings with '+' work the same way as QStringBuilder's '%'.

Note: Using automatic type deduction (for example, by using the auto keyword) with the result of string concatenation when QStringBuilder is enabled will show that the concatenation is indeed an object of a QStringBuilder specialization:

     QString str("QStringBuilder");

     // "s" type is deduced as QStringBuilder<...>
     auto s = "Like hot glue, " % str % " concatenates strings";

     // Similarly the return type of this lambda is deduced as QStringBuilder<...>
     auto concatenateStr = []() {
         return "Like hot glue, " % str % " concatenates strings";
     };

This does not cause any harm, as QStringBuilder will implicitly convert to QString when required. If this is undesirable, then one should specify the necessary types instead of having the compiler deduce them:

     QString s = "Like hot glue, " % str % " concatenates strings";

     // With a lambda, specify a trailing return type:
     auto concatenateStr = []() -> QString {
         return "Like hot glue, " % str % " concatenates strings";
     };

Maximum size and out-of-memory conditions

The maximum size of QString depends on the architecture. Most 64-bit systems can allocate more than 2 GB of memory, with a typical limit of 2^63 bytes. The actual value also depends on the overhead required for managing the data block. As a result, you can expect a maximum size of 2 GB minus overhead on 32-bit platforms and 2^63 bytes minus overhead on 64-bit platforms. The number of elements that can be stored in a QString is this maximum size divided by the size of QChar.

When memory allocation fails, QString throws a std::bad_alloc exception if the application was compiled with exception support. Out-of-memory conditions in Qt containers are the only cases where Qt will throw exceptions. If exceptions are disabled, then running out of memory is undefined behavior.

Note: Target operating systems may impose limits on how much memory an application can allocate, in total, or on the size of individual allocations. This may further restrict the size of string a QString can hold. Mitigating or controlling the behavior these limits cause is beyond the scope of the Qt API.

See also fromRawData(), QChar, QStringView, QLatin1StringView, and QByteArray.

Member Type Documentation

QString::ConstIterator

Qt-style synonym for QString::const_iterator.

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

QString::const_iterator

See also QString::iterator.

QString::const_pointer

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

QString::const_reference

QString::const_reverse_iterator

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

QString::difference_type

QString::iterator

See also QString::const_iterator.

QString::pointer

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

QString::reference

QString::reverse_iterator

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

QString::size_type

QString::value_type

Member Function Documentation

QString QString::left(qsizetype n) &&

QString QString::left(qsizetype n) const &

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

If you know that n cannot be out of bounds, use first() instead in new code, because it is faster.

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

See also first(), last(), startsWith(), chopped(), chop(), and truncate().

QString QString::right(qsizetype n) const &

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

If you know that n cannot be out of bounds, use last() instead in new code, because it is faster.

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

See also endsWith(), last(), first(), sliced(), chopped(), chop(), truncate(), and slice().

QString QString::mid(qsizetype position, qsizetype n = -1) &&

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

Returns a string that contains n characters of this string, starting at the specified position index.

If you know that position and n cannot be out of bounds, use sliced() instead in new code, because it is faster.

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.

See also first(), last(), sliced(), chopped(), chop(), truncate(), and slice().

[since 6.0] QString QString::first(qsizetype n) &&

[since 6.0] QString QString::first(qsizetype n) const &

Returns a string that contains the first n characters of this string.

Note: The behavior is undefined when n < 0 or n > size().

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

This function was introduced in Qt 6.0.

See also last(), sliced(), startsWith(), chopped(), chop(), truncate(), and slice().

[since 6.0] QString QString::last(qsizetype n) &&

[since 6.0] QString QString::last(qsizetype n) const &

Returns the string that contains the last n characters of this string.

Note: The behavior is undefined when n < 0 or n > size().

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

This function was introduced in Qt 6.0.

See also first(), sliced(), endsWith(), chopped(), chop(), truncate(), and slice().

[since 6.0] QString QString::sliced(qsizetype pos, qsizetype n) &&

[since 6.0] QString QString::sliced(qsizetype pos, qsizetype n) const &

Returns a string that contains n characters of this string, starting at position pos.

Note: The behavior is undefined when pos < 0, n < 0, or pos + n > size().

 QString x = "Nine pineapples";
 QString y = x.sliced(5, 4);            // y == "pine"
 QString z = x.sliced(5);               // z == "pineapples"

This function was introduced in Qt 6.0.

See also first(), last(), chopped(), chop(), truncate(), and slice().

[since 6.0] QString QString::sliced(qsizetype pos) &&

[since 6.0] QString QString::sliced(qsizetype pos) const &

This is an overloaded function.

Returns a string that contains the portion of this string starting at position pos and extending to its end.

Note: The behavior is undefined when pos < 0 or pos > size().

This function was introduced in Qt 6.0.

See also first(), last(), chopped(), chop(), truncate(), and slice().

QString QString::chopped(qsizetype len) &&

QString QString::chopped(qsizetype len) const &

Returns a string that contains the size() - len leftmost characters of this string.

Note: The behavior is undefined if len is negative or greater than size().

See also endsWith(), first(), last(), sliced(), chop(), truncate(), and slice().

[static constexpr noexcept, since 6.8] qsizetype QString::maxSize()

[constexpr noexcept, since 6.8] qsizetype QString::max_size() const

It returns the maximum number of elements that the string can theoretically hold. In practice, the number can be much smaller, limited by the amount of memory available to the system.

This function was introduced in Qt 6.8.

template <typename... Args> QString QString::arg(Args &&... args) const

Replaces occurrences of %N in this string with the corresponding argument from args. The arguments are not positional: the first of the args replaces the %N with the lowest N (all of them), the second of the args the %N with the next-lowest N etc.

Args can consist of anything that implicitly converts to QString, QStringView or QLatin1StringView.

In addition, the following types are also supported: QChar, QLatin1Char.

See also QString::arg().

[noexcept(...), since 6.0] template <typename Needle, typename... Flags> auto QString::tokenize(Needle &&sep, Flags... flags) &&

[noexcept(...), since 6.0] template <typename Needle, typename... Flags> auto QString::tokenize(Needle &&sep, Flags... flags) const &

[noexcept(...), since 6.0] template <typename Needle, typename... Flags> auto QString::tokenize(Needle &&sep, Flags... flags) const &&

Splits the string into substring views wherever sep occurs, and returns a lazy sequence of those strings.

Equivalent to

 return QStringTokenizer{std::forward<Needle>(sep), flags...};

except it works without C++17 Class Template Argument Deduction (CTAD) enabled in the compiler.

See QStringTokenizer for how sep and flags interact to form the result.

Note: While this function returns QStringTokenizer, you should never, ever, name its template arguments explicitly. If you can use C++17 Class Template Argument Deduction (CTAD), you may write

 QStringTokenizer result = sv.tokenize(sep);

(without template arguments). If you can't use C++17 CTAD, you must store the return value only in auto variables:

 auto result = sv.tokenize(sep);

This is because the template arguments of QStringTokenizer have a very subtle dependency on the specific tokenize() overload from which they are returned, and they don't usually correspond to the type used for the separator.

This function was introduced in Qt 6.0.

Note: (1) does not throw any exception when "noexcept(qTokenize(std::declval<QString>(), std::forward<Needle>(needle), flags...))" is true.

Note: (2) does not throw any exception when "noexcept(qTokenize(std::declval<const QString &>(), std::forward<Needle>(needle), flags...))" is true.

Note: (3) does not throw any exception when "noexcept(qTokenize(std::declval<const QString>(), std::forward<Needle>(needle), flags...))" is true.

See also QStringTokenizer and qTokenize().

[constexpr noexcept] QString::QString()

Constructs a null string. Null strings are also considered empty.

See also isEmpty(), isNull(), and Distinction Between Null and Empty Strings.

QString::QString(QChar ch)

Constructs a string of size 1 containing the character ch.

QString::QString(QLatin1StringView str)

Constructs a copy of the Latin-1 string viewed by str.

See also fromLatin1().

QString::QString(const QByteArray &ba)

Constructs a string initialized with the byte array ba. The given byte array is converted to Unicode using fromUtf8().

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.

Note: Any null ('\0') bytes in the byte array will be included in this string, converted to Unicode null characters (U+0000). This behavior is different from Qt 5.x.

See also fromLatin1(), fromLocal8Bit(), and fromUtf8().

QString::QString(const char *str)

Constructs a string initialized with the 8-bit string str. The given const char pointer is converted to Unicode using the fromUtf8() 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.

Note: Defining QT_RESTRICTED_CAST_FROM_ASCII also disables this constructor, but enables a QString(const char (&ch)[N]) constructor instead. Using non-literal input, or input with embedded NUL characters, or non-7-bit characters is undefined in this case.

See also fromLatin1(), fromLocal8Bit(), and fromUtf8().

[since 6.1] QString::QString(const char8_t *str)

Constructs a string initialized with the UTF-8 string str. The given const char8_t pointer is converted to Unicode using the fromUtf8() function.

This function was introduced in Qt 6.1.

See also fromLatin1(), fromLocal8Bit(), and fromUtf8().

[explicit] QString::QString(const QChar *unicode, qsizetype 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 \0'-terminated array and its length is determined dynamically. The terminating null 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(qsizetype size, QChar ch)

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

See also fill().

[noexcept] QString::QString(const QString &other)

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

[noexcept] QString::QString(QString &&other)

Move-constructs a QString instance, making it point at the same object that other was pointing to.

[noexcept] QString::~QString()

Destroys the string.

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(QLatin1StringView str)

This function overloads append().

Appends the Latin-1 string viewed by str to this string.

[since 6.0] QString &QString::append(QStringView v)

This function overloads append().

Appends the given string view v to this string and returns the result.

This function was introduced in Qt 6.0.

[since 6.5] QString &QString::append(QUtf8StringView str)

This function overloads append().

Appends the UTF-8 string view str to this string.

This function was introduced in Qt 6.5.

QString &QString::append(const QByteArray &ba)

This function overloads append().

Appends the byte array ba to this string. The given byte array is converted to Unicode using the fromUtf8() 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.

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

This function overloads append().

Appends the string str to this string. The given const char pointer is converted to Unicode using the fromUtf8() 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.

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

This function overloads append().

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

QString QString::arg(const QString &a, int fieldWidth = 0, QChar fillChar = u' ') 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(QChar a, int fieldWidth = 0, QChar fillChar = u' ') const

This function overloads arg().

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

This is an overloaded function.

Returns a copy of this string with the lowest-numbered place-marker replaced by the Latin-1 string viewed by 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.

QString QString::arg(QStringView a, int fieldWidth = 0, QChar fillChar = u' ') 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.

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

This function overloads arg().

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

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

This function overloads arg().

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.

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 '%' 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 system 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"

See also Number Formats.

QString QString::arg(long a, int fieldWidth = 0, int base = 10, QChar fillChar = u' ') 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 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"

See also Number Formats.

QString QString::arg(qlonglong a, int fieldWidth = 0, int base = 10, QChar fillChar = u' ') 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.

See also Number Formats.

QString QString::arg(qulonglong a, int fieldWidth = 0, int base = 10, QChar fillChar = u' ') 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.

See also Number Formats.

QString QString::arg(short a, int fieldWidth = 0, int base = 10, QChar fillChar = u' ') 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.

See also Number Formats.

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

This function overloads arg().

The base argument specifies the base to use when converting the integer a into a string. The base must be between 2 and 36.

See also Number Formats.

QString QString::arg(ulong a, int fieldWidth = 0, int base = 10, QChar fillChar = u' ') 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 to a string. The base must be between 2 and 36, with 8 giving octal, 10 decimal, and 16 hexadecimal numbers.

See also Number Formats.

QString QString::arg(ushort a, int fieldWidth = 0, int base = 10, QChar fillChar = u' ') 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.

See also Number Formats.

QString QString::arg(double a, int fieldWidth = 0, char format = 'g', int precision = -1, QChar fillChar = u' ') const

This function overloads arg().

Argument a is formatted according to the specified format and precision. See Floating-point Formats for details.

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.

 double d = 12.34;
 QString str = QString("delta: %1").arg(d, 0, 'E', 3);
 // str == "delta: 1.234E+01"

See also QLocale::toString(), QLocale::FloatingPointPrecisionOption, and Number Formats.

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

See also arg().

[since 6.6] QString &QString::assign(QAnyStringView v)

Replaces the contents of this string with a copy of v and returns a reference to this string.

The size of this string will be equal to the size of v, converted to UTF-16 as if by v.toString(). Unlike QAnyStringView::toString(), however, this function only allocates memory if the estimated size exceeds the capacity of this string or this string is shared.

This function was introduced in Qt 6.6.

See also QAnyStringView::toString().

[since 6.6] template <typename InputIterator, QString::if_compatible_iterator<InputIterator> = true> QString &QString::assign(InputIterator first, InputIterator last)

Replaces the contents of this string with a copy of the elements in the iterator range [first, last) and returns a reference to this string.

The size of this string will be equal to the decoded length of the elements in the range [first, last), which need not be the same as the length of the range itself, because this function transparently recodes the input character set to UTF-16.

This function will only allocate memory if the number of elements in the range, or, for non-UTF-16-encoded input, the maximum possible size of the resulting string, exceeds the capacity of this string, or if this string is shared.

Note: This function overload only participates in overload resolution if InputIterator meets the requirements of a LegacyInputIterator and the value_type of InputIterator is one of the following character types:

  • QChar
  • QLatin1Char
  • char
  • unsigned char
  • signed char
  • char8_t
  • char16_t
  • (on platforms, such as Windows, where it is a 16-bit type) wchar_t
  • char32_t

Note: The behavior is undefined if either argument is an iterator into *this or [first, last) is not a valid range.

This function was introduced in Qt 6.6.

[since 6.6] QString &QString::assign(qsizetype n, QChar c)

Replaces the contents of this string with n copies of c and returns a reference to this string.

The size of this string will be equal to n, which has to be non-negative.

This function will only allocate memory if n exceeds the capacity of this string or this string is shared.

This function was introduced in Qt 6.6.

See also fill().

const QChar QString::at(qsizetype position) const

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

QChar &QString::back()

Returns a reference to the last character in the string. Same as operator[](size() - 1).

This function is provided for STL compatibility.

Warning: Calling this function on an empty string constitutes undefined behavior.

See also front(), at(), and operator[]().

QChar QString::back() const

Returns the last character in the string. Same as at(size() - 1).

This function is provided for STL compatibility.

Warning: Calling this function on an empty string constitutes undefined behavior.

See also front(), at(), and operator[]().

QString::iterator QString::begin()

Returns an STL-style iterator pointing to the first character in the string.

Warning: The returned iterator is invalidated on detachment or when the QString is modified.

See also constBegin() and end().

QString::const_iterator QString::begin() const

This function overloads begin().

qsizetype QString::capacity() const

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

Note: a statically allocated string will report a capacity of 0, even if it's not empty.

Note: The free space position in the allocated memory block is undefined. In other words, one should not assume that the free memory is always located after the initialized elements.

See also reserve() and squeeze().

QString::const_iterator QString::cbegin() const

Returns a const STL-style iterator pointing to the first character in the string.

Warning: The returned iterator is invalidated on detachment or when the QString is modified.

See also begin() and cend().

QString::const_iterator QString::cend() const

Returns a const STL-style iterator pointing just after the last character in the string.

Warning: The returned iterator is invalidated on detachment or when the QString is modified.

See also cbegin() and end().

void QString::chop(qsizetype 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 QStringView::chop().

void QString::clear()

Clears the contents of the string and makes it null.

See also resize() and isNull().

[static noexcept] int QString::compare(const QString &s1, const QString &s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)

Compares the string s1 with the string s2 and returns a negative integer if s1 is less than s2, a positive integer if it is greater than s2, and zero if they are equal.

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

Note: This function treats null strings the same as empty strings, for more details see Distinction Between Null and Empty Strings.

See also operator==(), operator<(), operator>(), and Comparing Strings.

[noexcept] int QString::compare(QChar ch, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

This function overloads compare().

Performs a comparison of this with ch, using the case sensitivity setting cs.

[noexcept] int QString::compare(QLatin1StringView other, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

This function overloads compare().

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

[noexcept] int QString::compare(QStringView s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

This function overloads compare().

Performs a comparison of this with s, using the case sensitivity setting cs.

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

This function overloads compare().

Lexically compares this string with the string other and returns a negative integer if this string is less than other, a positive integer if it is greater than other, and zero if they are equal.

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

[static noexcept] int QString::compare(QLatin1StringView s1, const QString &s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)

This function overloads compare().

Performs a comparison of s1 and s2, using the case sensitivity setting cs.

[static noexcept] int QString::compare(QStringView s1, const QString &s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)

This function overloads compare().

[static noexcept] int QString::compare(const QString &s1, QLatin1StringView s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)

This function overloads compare().

Performs a comparison of s1 and s2, using the case sensitivity setting cs.

[static noexcept] int QString::compare(const QString &s1, QStringView s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)

This function overloads compare().

QString::const_iterator QString::constBegin() const

Returns a const STL-style iterator pointing to the first character in the string.

Warning: The returned iterator is invalidated on detachment or when the QString is modified.

See also begin() and constEnd().

const QChar *QString::constData() const

Returns a pointer to the data stored in the QString. The pointer can be used to access the characters that compose the string.

Note that the pointer remains valid only as long as the string is not modified.

Note: The returned string may not be '\0'-terminated. Use size() to determine the length of the array.

See also data(), operator[](), and fromRawData().

QString::const_iterator QString::constEnd() const

Returns a const STL-style iterator pointing just after the last character in the string.

Warning: The returned iterator is invalidated on detachment or when the QString is modified.

See also constBegin() and end().

bool QString::contains(const QRegularExpression &re, QRegularExpressionMatch *rmatch = nullptr) const

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

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

See also QRegularExpression::match().

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

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

bool QString::contains(QChar ch, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

This function overloads contains().

Returns true if this string contains an occurrence of the character ch; otherwise returns false.

bool QString::contains(QLatin1StringView str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

This function overloads contains().

Returns true if this string contains an occurrence of the latin-1 string str; otherwise returns false.

[noexcept] bool QString::contains(QStringView str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

This function overloads contains().

Returns true if this string contains an occurrence of the string view str; otherwise returns false.

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

See also indexOf() and count().

qsizetype 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 (the default), the search is case-sensitive; otherwise the search is case-insensitive.

See also contains() and indexOf().

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

This function overloads count().

Returns the number of times the regular expression re matches in the string.

For historical reasons, 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 behavior is different from simply iterating over the matches in the string using QRegularExpressionMatchIterator.

See also QRegularExpression::globalMatch().

qsizetype 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 (the default), the search is case-sensitive; otherwise the search is case-insensitive.

See also contains() and indexOf().

[since 6.0] qsizetype QString::count(QStringView str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

This function overloads count().

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

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

This function was introduced in Qt 6.0.

See also contains() and indexOf().

QString::const_reverse_iterator QString::crbegin() const

Returns a const STL-style reverse iterator pointing to the first character in the string, in reverse order.

Warning: The returned iterator is invalidated on detachment or when the QString is modified.

See also begin(), rbegin(), and rend().

QString::const_reverse_iterator QString::crend() const

Returns a const STL-style reverse iterator pointing just after the last character in the string, in reverse order.

Warning: The returned iterator is invalidated on detachment or when the QString is modified.

See also end(), rend(), and rbegin().

QChar *QString::data()

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.

Unlike constData() and unicode(), the returned data is always '\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[]().

const QChar *QString::data() const

This is an overloaded function.

Note: The returned string may not be '\0'-terminated. Use size() to determine the length of the array.

See also fromRawData().

QString::iterator QString::end()

Returns an STL-style iterator pointing just after the last character in the string.

Warning: The returned iterator is invalidated on detachment or when the QString is modified.

See also begin() and constEnd().

QString::const_iterator QString::end() const

This function overloads end().

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

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

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

This function overloads endsWith().

[noexcept] bool QString::endsWith(QStringView str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

This function overloads endsWith().

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

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

See also startsWith().

[since 6.1] QString::iterator QString::erase(QString::const_iterator first, QString::const_iterator last)

Removes from the string the characters in the half-open range [ first , last ). Returns an iterator to the character immediately after the last erased character (i.e. the character referred to by last before the erase).

This function was introduced in Qt 6.1.

[since 6.5] QString::iterator QString::erase(QString::const_iterator it)

This is an overloaded function.

Removes the character denoted by it from the string. Returns an iterator to the character immediately after the erased character.

 QString c = "abcdefg";
 auto it = c.erase(c.cbegin()); // c is now "bcdefg"; "it" points to "b"

This function was introduced in Qt 6.5.

QString &QString::fill(QChar ch, qsizetype 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 macOS and iOS.

[static, since 6.6] QString QString::fromEcmaString(emscripten::val jsString)

Converts the ECMAScript string jsString to QString. Behavior is undefined if the provided parameter is not a string.

This function was introduced in Qt 6.6.

See also toEcmaString().

[static] QString QString::fromLatin1(const char *str, qsizetype size)

Returns a QString initialized with the first size characters of the Latin-1 string str.

If size is -1, strlen(str) is used instead.

See also toLatin1(), fromUtf8(), and fromLocal8Bit().

[static, since 6.0] QString QString::fromLatin1(QByteArrayView str)

This is an overloaded function.

Returns a QString initialized with the Latin-1 string str.

Note: : any null ('\0') bytes in the byte array will be included in this string, converted to Unicode null characters (U+0000).

This function was introduced in Qt 6.0.

[static] QString QString::fromLatin1(const QByteArray &str)

This is an overloaded function.

Returns a QString initialized with the Latin-1 string str.

Note: : any null ('\0') bytes in the byte array will be included in this string, converted to Unicode null characters (U+0000). This behavior is different from Qt 5.x.

[static] QString QString::fromLocal8Bit(const char *str, qsizetype size)

Returns a QString initialized with the first size characters of the 8-bit string str.

If size is -1, strlen(str) is used instead.

On Unix systems this is equivalent to fromUtf8(). Note that on Apple systems this function does not take NSString.defaultCStringEncoding or CFStringGetSystemEncoding() into account, as these functions typically return the legacy "Western (Mac OS Roman)" encoding, which should not be used on modern Apple operating systems. On Windows the system's current code page is used.

See also toLocal8Bit(), fromLatin1(), and fromUtf8().

[static, since 6.0] QString QString::fromLocal8Bit(QByteArrayView str)

This is an overloaded function.

Returns a QString initialized with the 8-bit string str.

On Unix systems this is equivalent to fromUtf8(). Note that on Apple systems this function does not take NSString.defaultCStringEncoding or CFStringGetSystemEncoding() into account, as these functions typically return the legacy "Western (Mac OS Roman)" encoding, which should not be used on modern Apple operating systems. On Windows the system's current code page is used.

Note: : any null ('\0') bytes in the byte array will be included in this string, converted to Unicode null characters (U+0000).

This function was introduced in Qt 6.0.

[static] QString QString::fromLocal8Bit(const QByteArray &str)

This is an overloaded function.

Returns a QString initialized with the 8-bit string str.

On Unix systems this is equivalent to fromUtf8(). Note that on Apple systems this function does not take NSString.defaultCStringEncoding or CFStringGetSystemEncoding() into account, as these functions typically return the legacy "Western (Mac OS Roman)" encoding, which should not be used on modern Apple operating systems. On Windows the system's current code page is used.

Note: : any null ('\0') bytes in the byte array will be included in this string, converted to Unicode null characters (U+0000). This behavior is different from Qt 5.x.

[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 macOS and iOS.

[static] QString QString::fromRawData(const QChar *unicode, qsizetype 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};
 qsizetype 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::fromStdString(const std::string &str)

Returns a copy of the str string. The given string is assumed to be encoded in UTF-8, and is converted to QString using the fromUtf8() function.

See also fromLatin1(), fromLocal8Bit(), fromUtf8(), and QByteArray::fromStdString().

[static] QString QString::fromStdU16String(const std::u16string &str)

Returns a copy of the str string. The given string is assumed to be encoded in UTF-16, and is converted to QString using the fromUtf16() function.

See also fromUtf16(), fromStdWString(), and fromStdU32String().

[static] QString QString::fromStdU32String(const std::u32string &str)

Returns a copy of the str string. The given string is assumed to be encoded in UCS-4, and is converted to QString using the fromUcs4() function.

See also fromUcs4(), fromStdWString(), and fromStdU16String().

[static] QString QString::fromStdWString(const std::wstring &str)

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

See also fromUtf16(), fromLatin1(), fromLocal8Bit(), fromUtf8(), fromUcs4(), fromStdU16String(), and fromStdU32String().

[static] QString QString::fromUcs4(const char32_t *unicode, qsizetype 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 \0'-terminated.

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

[static] QString QString::fromUtf8(const char *str, qsizetype size)

Returns a QString initialized with the first size bytes of the UTF-8 string str.

If size is -1, strlen(str) is used instead.

UTF-8 is a Unicode codec and can represent all characters in a Unicode string like QString. However, invalid sequences are possible with UTF-8 and, if any such are found, they will be replaced with one or more "replacement characters", or suppressed. These include non-Unicode sequences, non-characters, overlong sequences or surrogate codepoints encoded into UTF-8.

This function can be used to process incoming data incrementally as long as all UTF-8 characters are terminated within the incoming data. Any unterminated characters at the end of the string will be replaced or suppressed. In order to do stateful decoding, please use QStringDecoder.

See also toUtf8(), fromLatin1(), and fromLocal8Bit().

[static, since 6.0] QString QString::fromUtf8(QByteArrayView str)

This is an overloaded function.

Returns a QString initialized with the UTF-8 string str.

Note: : any null ('\0') bytes in the byte array will be included in this string, converted to Unicode null characters (U+0000).

This function was introduced in Qt 6.0.

[static] QString QString::fromUtf8(const QByteArray &str)

This is an overloaded function.

Returns a QString initialized with the UTF-8 string str.

Note: : any null ('\0') bytes in the byte array will be included in this string, converted to Unicode null characters (U+0000). This behavior is different from Qt 5.x.

[static, since 6.1] QString QString::fromUtf8(const char8_t *str)

This is an overloaded function.

This overload is only available when compiling in C++20 mode.

This function was introduced in Qt 6.1.

[static, since 6.0] QString QString::fromUtf8(const char8_t *str, qsizetype size)

This is an overloaded function.

This overload is only available when compiling in C++20 mode.

This function was introduced in Qt 6.0.

[static] QString QString::fromUtf16(const char16_t *unicode, qsizetype 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 \0'-terminated.

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 *, qsizetype) or QString(const QChar *) if possible.

QString makes a deep copy of the Unicode data.

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

[static] QString QString::fromWCharArray(const wchar_t *string, qsizetype size = -1)

Returns a copy of the string, where the encoding of string depends on the size of wchar. If wchar is 4 bytes, the string is interpreted as UCS-4, if wchar is 2 bytes it is interpreted as UTF-16.

If size is -1 (default), the string must be '\0'-terminated.

See also fromUtf16(), fromLatin1(), fromLocal8Bit(), fromUtf8(), fromUcs4(), and fromStdWString().

QChar &QString::front()

Returns a reference to the first character in the string. Same as operator[](0).

This function is provided for STL compatibility.

Warning: Calling this function on an empty string constitutes undefined behavior.

See also back(), at(), and operator[]().

QChar QString::front() const

Returns the first character in the string. Same as at(0).

This function is provided for STL compatibility.

Warning: Calling this function on an empty string constitutes undefined behavior.

See also back(), at(), and operator[]().

qsizetype QString::indexOf(QLatin1StringView str, qsizetype from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

Returns the index position of the first occurrence of the Latin-1 string viewed by 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().

qsizetype QString::indexOf(const QRegularExpression &re, qsizetype from = 0, QRegularExpressionMatch *rmatch = nullptr) const

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 nullptr, it also writes the results of the match into the QRegularExpressionMatch object pointed to by rmatch.

Example:

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

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

qsizetype QString::indexOf(const QString &str, qsizetype 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 (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().

qsizetype QString::indexOf(QChar ch, qsizetype 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 this string, searching forward from index position from. Returns -1 if ch is not found.

[noexcept] qsizetype QString::indexOf(QStringView str, qsizetype from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

This function overloads indexOf().

Returns the index position of the first occurrence of the string view 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.

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 QStringView::indexOf(), lastIndexOf(), contains(), and count().

QString &QString::insert(qsizetype position, const QString &str)

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"

This string grows to accommodate the insertion. If position is beyond the end of the string, space characters are appended to the string to reach this position, followed by str.

See also append(), prepend(), replace(), and remove().

QString &QString::insert(qsizetype position, QChar ch)

This function overloads insert().

Inserts ch at the given index position in the string.

This string grows to accommodate the insertion. If position is beyond the end of the string, space characters are appended to the string to reach this position, followed by ch.

QString &QString::insert(qsizetype position, QLatin1StringView str)

This function overloads insert().

Inserts the Latin-1 string viewed by str at the given index position.

This string grows to accommodate the insertion. If position is beyond the end of the string, space characters are appended to the string to reach this position, followed by str.

[since 6.0] QString &QString::insert(qsizetype position, QStringView str)

This function overloads insert().

Inserts the string view str at the given index position and returns a reference to this string.

This string grows to accommodate the insertion. If position is beyond the end of the string, space characters are appended to the string to reach this position, followed by str.

This function was introduced in Qt 6.0.

[since 6.5] QString &QString::insert(qsizetype position, QUtf8StringView str)

This function overloads insert().

Inserts the UTF-8 string view str at the given index position.

Note: Inserting variable-width UTF-8-encoded string data is conceptually slower than inserting fixed-width string data such as UTF-16 (QStringView) or Latin-1 (QLatin1StringView) and should thus be used sparingly.

This string grows to accommodate the insertion. If position is beyond the end of the string, space characters are appended to the string to reach this position, followed by str.

This function was introduced in Qt 6.5.

QString &QString::insert(qsizetype position, const QByteArray &str)

This function overloads insert().

Interprets the contents of str as UTF-8, inserts the Unicode string it encodes at the given index position and returns a reference to this string.

This string grows to accommodate the insertion. If position is beyond the end of the string, space characters are appended to the string to reach this position, followed by str.

This function is not available when QT_NO_CAST_FROM_ASCII is defined.

QString &QString::insert(qsizetype position, const char *str)

This function overloads insert().

Inserts the C string str at the given index position and returns a reference to this string.

This string grows to accommodate the insertion. If position is beyond the end of the string, space characters are appended to the string to reach this position, followed by str.

This function is not available when QT_NO_CAST_FROM_ASCII is defined.

QString &QString::insert(qsizetype position, const QChar *unicode, qsizetype size)

This function overloads insert().

Inserts the first size characters of the QChar array unicode at the given index position in the string.

This string grows to accommodate the insertion. If position is beyond the end of the string, space characters are appended to the string to reach this position, followed by size characters of the QChar array unicode.

[noexcept] bool QString::isEmpty() const

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

bool QString::isLower() const

Returns true if the string is lowercase, that is, it's identical to its toLower() folding.

Note that this does not mean that the string does not contain uppercase letters (some uppercase letters do not have a lowercase folding; they are left unchanged by toLower()). For more information, refer to the Unicode standard, section 3.13.

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

bool QString::isNull() const

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

bool QString::isRightToLeft() const

Returns true if the string is read right to left.

See also QStringView::isRightToLeft().

bool QString::isUpper() const

Returns true if the string is uppercase, that is, it's identical to its toUpper() folding.

Note that this does not mean that the string does not contain lowercase letters (some lowercase letters do not have a uppercase folding; they are left unchanged by toUpper()). For more information, refer to the Unicode standard, section 3.13.

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

[noexcept] bool QString::isValidUtf16() const

Returns true if the string contains valid UTF-16 encoded data, or false otherwise.

Note that this function does not perform any special validation of the data; it merely checks if it can be successfully decoded from UTF-16. The data is assumed to be in host byte order; the presence of a BOM is meaningless.

See also QStringView::isValidUtf16().

qsizetype QString::lastIndexOf(const QRegularExpression &re, qsizetype from, QRegularExpressionMatch *rmatch = nullptr) const

Returns the index position of the last match of the regular expression re in the string, which starts before the index position from.

If from is -1, the search starts at the last character; if it is -2, at the next to last character and so on.

Returns -1 if re didn't match anywhere.

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

Example:

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

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

Note: Due to how the regular expression matching algorithm works, this function will actually match repeatedly from the beginning of the string until the position from is reached.

Note: When searching for a regular expression re that may match 0 characters, the match at the end of the data is excluded from the search by a negative from, even though -1 is normally thought of as searching from the end of the string: the match at the end is after the last character, so it is excluded. To include such a final empty match, either give a positive value for from or omit the from parameter entirely.

qsizetype QString::lastIndexOf(const QString &str, qsizetype from, 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, the search starts at the last character; if it 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

Note: When searching for a 0-length str, the match at the end of the data is excluded from the search by a negative from, even though -1 is normally thought of as searching from the end of the string: the match at the end is after the last character, so it is excluded. To include such a final empty match, either give a positive value for from or omit the from parameter entirely.

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

[noexcept, since 6.3] qsizetype QString::lastIndexOf(QChar ch, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

This function overloads lastIndexOf().

This function was introduced in Qt 6.3.

[since 6.2] qsizetype QString::lastIndexOf(QLatin1StringView str, 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. 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

This function was introduced in Qt 6.2.

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

[noexcept, since 6.2] qsizetype QString::lastIndexOf(QStringView str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

This function overloads lastIndexOf().

Returns the index position of the last occurrence of the string view str in this string. 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.

This function was introduced in Qt 6.2.

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

[since 6.2] qsizetype QString::lastIndexOf(const QRegularExpression &re, QRegularExpressionMatch *rmatch = nullptr) const

This function overloads lastIndexOf().

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

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

Example:

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

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

Note: Due to how the regular expression matching algorithm works, this function will actually match repeatedly from the beginning of the string until the end of the string is reached.

This function was introduced in Qt 6.2.

[since 6.2] qsizetype QString::lastIndexOf(const QString &str, 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. 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

This function was introduced in Qt 6.2.

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

qsizetype QString::lastIndexOf(QChar ch, qsizetype from, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

This function overloads lastIndexOf().

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

qsizetype QString::lastIndexOf(QLatin1StringView str, qsizetype from, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

This function overloads lastIndexOf().

Returns the index position of the last occurrence of the Latin-1 string viewed by str in this string, searching backward from index position from.

If from is -1, the search starts at the last character; if it 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

Note: When searching for a 0-length str, the match at the end of the data is excluded from the search by a negative from, even though -1 is normally thought of as searching from the end of the string: the match at the end is after the last character, so it is excluded. To include such a final empty match, either give a positive value for from or omit the from parameter entirely.

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

[noexcept] qsizetype QString::lastIndexOf(QStringView str, qsizetype from, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

This function overloads lastIndexOf().

Returns the index position of the last occurrence of the string view str in this string, searching backward from index position from.

If from is -1, the search starts at the last character; if it 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.

Note: When searching for a 0-length str, the match at the end of the data is excluded from the search by a negative from, even though -1 is normally thought of as searching from the end of the string: the match at the end is after the last character, so it is excluded. To include such a final empty match, either give a positive value for from or omit the from parameter entirely.

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

QString QString::leftJustified(qsizetype width, QChar fill = u' ', 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().

[noexcept] qsizetype QString::length() const

Returns the number of characters in this string. Equivalent to size().

See also resize().

[static] int QString::localeAwareCompare(const QString &s1, const QString &s2)

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.

See also compare(), QLocale, and Comparing Strings.

[since 6.0] int QString::localeAwareCompare(QStringView 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).

This function was introduced in Qt 6.0.

See also Comparing Strings.

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

See also Comparing Strings.

[static, since 6.0] int QString::localeAwareCompare(QStringView s1, QStringView s2)

This function overloads localeAwareCompare().

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.

This function was introduced in Qt 6.0.

See also Comparing Strings.

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(long n, int base = 10)

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.

The formatting always uses QLocale::C, i.e., English/UnitedStates. To get a localized string representation of a number, use QLocale::toString() with the appropriate locale.

 long a = 63;
 QString s = QString::number(a, 16);             // s == "3f"
 QString t = QString::number(a, 16).toUpper();     // t == "3F"

See also setNum().

[static] QString QString::number(double n, char format = 'g', int precision = 6)

Returns a string representing the floating-point number n.

Returns a string that represents n, formatted according to the specified format and precision.

For formats with an exponent, the exponent will show its sign and have at least two digits, left-padding the exponent with zero if needed.

See also setNum(), QLocale::toString(), QLocale::FloatingPointPrecisionOption, and Number Formats.

[static] QString QString::number(int 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.

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

This is an overloaded function.

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

This is an overloaded function.

QString &QString::prepend(const QString &str)

Prepends the string str to the beginning of this string and returns a reference to this string.

This operation is typically very fast (constant time), because QString preallocates extra space at the beginning of the string data, so it can grow without reallocating the entire string each time.

Example:

 QString x = "ship";
 QString y = "air";
 x.prepend(y);
 // x == "airship"

See also append() and insert().

QString &QString::prepend(QChar ch)

This function overloads prepend().

Prepends the character ch to this string.

QString &QString::prepend(QLatin1StringView str)

This function overloads prepend().

Prepends the Latin-1 string viewed by str to this string.

[since 6.0] QString &QString::prepend(QStringView str)

This function overloads prepend().

Prepends the string view str to the beginning of this string and returns a reference to this string.

This function was introduced in Qt 6.0.

[since 6.5] QString &QString::prepend(QUtf8StringView str)

This function overloads prepend().

Prepends the UTF-8 string view str to this string.

This function was introduced in Qt 6.5.

QString &QString::prepend(const QByteArray &ba)

This function overloads prepend().

Prepends the byte array ba to this string. The byte array is converted to Unicode using the fromUtf8() 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.

QString &QString::prepend(const char *str)

This function overloads prepend().

Prepends the string str to this string. The const char pointer is converted to Unicode using the fromUtf8() 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.

QString &QString::prepend(const QChar *str, qsizetype len)

This function overloads prepend().

Prepends len characters from the QChar array str to this string and returns a reference to this string.

void QString::push_back(const QString &other)

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

void QString::push_back(QChar ch)

This is an overloaded function.

Appends the given ch character onto the end of this string.

void QString::push_front(const QString &other)

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

void QString::push_front(QChar ch)

This is an overloaded function.

Prepends the given ch character to the beginning of this string.

QString::reverse_iterator QString::rbegin()

Returns a STL-style reverse iterator pointing to the first character in the string, in reverse order.

Warning: The returned iterator is invalidated on detachment or when the QString is modified.

See also begin(), crbegin(), and rend().

QString::const_reverse_iterator QString::rbegin() const

This is an overloaded function.

QString &QString::remove(const QRegularExpression &re)

Removes every occurrence of the regular expression re in the string, and returns a reference to the string. For example:

 QString r = "Telephone";
 r.remove(QRegularExpression("[aeiou]."));
 // r == "The"

Element removal will preserve the string's capacity and not reduce the amount of allocated memory. To shed extra capacity and free as much memory as possible, call squeeze() after the last change to the string's size.

See also indexOf(), lastIndexOf(), and replace().

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

Element removal will preserve the string's capacity and not reduce the amount of allocated memory. To shed extra capacity and free as much memory as possible, call squeeze() after the last change to the string's size.

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 (the default), the search is case-sensitive; otherwise the search is case-insensitive.

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

Element removal will preserve the string's capacity and not reduce the amount of allocated memory. To shed extra capacity and free as much memory as possible, call squeeze() after the last change to the string's size.

See also replace().

QString &QString::remove(qsizetype position, qsizetype n)

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.

If n is <= 0 nothing is changed.

 QString s = "Montreal";
 s.remove(1, 4);
 // s == "Meal"

Element removal will preserve the string's capacity and not reduce the amount of allocated memory. To shed extra capacity and free as much memory as possible, call squeeze() after the last change to the string's size.

See also insert() and replace().

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

This is an overloaded function.

Removes every occurrence of the given Latin-1 string viewed by str from 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).

Element removal will preserve the string's capacity and not reduce the amount of allocated memory. To shed extra capacity and free as much memory as possible, call squeeze() after the last change to the string's size.

See also replace().

[since 6.5] QString &QString::removeAt(qsizetype pos)

Removes the character at index pos. If pos is out of bounds (i.e. pos >= size()), this function does nothing.

This function was introduced in Qt 6.5.

See also remove().

[since 6.5] QString &QString::removeFirst()

Removes the first character in this string. If the string is empty, this function does nothing.

This function was introduced in Qt 6.5.

See also remove().

[since 6.1] template <typename Predicate> QString &QString::removeIf(Predicate pred)

Removes all elements for which the predicate pred returns true from the string. Returns a reference to the string.

This function was introduced in Qt 6.1.

See also remove().

[since 6.5] QString &QString::removeLast()

Removes the last character in this string. If the string is empty, this function does nothing.

This function was introduced in Qt 6.5.

See also remove().

QString::reverse_iterator QString::rend()

Returns a STL-style reverse iterator pointing just after the last character in the string, in reverse order.

Warning: The returned iterator is invalidated on detachment or when the QString is modified.

See also end(), crend(), and rbegin().

QString::const_reverse_iterator QString::rend() const

This is an overloaded function.

QString QString::repeated(qsizetype 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"

QString &QString::replace(qsizetype position, qsizetype n, const QString &after)

Replaces n characters beginning at index position with the string after and returns a reference to this string.

Note: If the specified position index is within the string, but position + n goes outside the strings range, then n will be adjusted to stop at the end of the string.

Example:

 QString x = "Say yes!";
 QString y = "no";
 x.replace(4, 3, y);
 // x == "Say no!"

See also insert() and remove().

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}."

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

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 (the default), the search is case-sensitive; otherwise the search is case-insensitive.

QString &QString::replace(QChar c, QLatin1StringView 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 (the default), the search is case-sensitive; otherwise the search is case-insensitive.

Note: The text is not rescanned after a replacement.

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 (the default), the search is case-sensitive; otherwise the search is case-insensitive.

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

This function overloads replace().

Replaces every occurrence in this string of the Latin-1 string viewed by before with the Latin-1 string viewed by after, 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.

Note: The text is not rescanned after a replacement.

Note: If you use an empty before argument, the after argument will be inserted before and after each character of the string.

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

This function overloads replace().

Replaces every occurrence in this string of the Latin-1 string viewed by before with the string after, 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.

Note: The text is not rescanned after a replacement.

Note: If you use an empty before argument, the after argument will be inserted before and after each character of the string.

QString &QString::replace(const QString &before, QLatin1StringView 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 (the default), the search is case-sensitive; otherwise the search is case-insensitive.

Note: The text is not rescanned after a replacement.

Note: If you use an empty before argument, the after argument will be inserted before and after each character of the string.

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

Note: If you use an empty before argument, the after argument will be inserted before and after each character of the string.

QString &QString::replace(qsizetype position, qsizetype n, QChar after)

This function overloads replace().

Replaces n characters beginning at index position with the character after and returns a reference to this string.

QString &QString::replace(qsizetype position, qsizetype n, const QChar *after, qsizetype alen)

This function overloads replace().

Replaces n characters beginning at index position with the first alen characters of the QChar array after and returns a reference to this string.

QString &QString::replace(const QChar *before, qsizetype blen, const QChar *after, qsizetype 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 (the default), the search is case-sensitive; otherwise the search is case-insensitive.

Note: If before points to an empty string (that is, blen == 0), the string pointed to by after will be inserted before and after each character in this string.

void QString::reserve(qsizetype size)

Ensures the string has space for at least size characters.

If you know in advance how large a string will be, you can call this function to save repeated reallocation while building it. This can improve performance when building a string incrementally. A long sequence of operations that add to a string may trigger several reallocations, the last of which may leave you with significantly more space than you need. This is less efficient than doing a single allocation of the right size at the start.

If in doubt about how much space shall be needed, it is usually better to use an upper bound as size, or a high estimate of the most likely size, if a strict upper bound would be much bigger than this. If size is an underestimate, the string will grow as needed once the reserved size is exceeded, which may lead to a larger allocation than your best overestimate would have and will slow the operation that triggers it.

Warning: reserve() reserves memory but does not change the size of the string. Accessing data beyond the end of the string is undefined behavior. If you need to access memory beyond the current end of the string, use resize().

This function is useful for code that needs to build up a long string and wants to avoid repeated reallocation. In this example, we want to add to the string until some condition is true, and we're fairly sure that size is large enough to make a call to reserve() worthwhile:

 QString result;
 qsizetype maxSize;
 bool condition;
 QChar nextChar;

 result.reserve(maxSize);

 while (condition)
     result.append(nextChar);

 result.squeeze();

See also squeeze(), capacity(), and resize().

void QString::resize(qsizetype 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 beyond position size are excluded from the string.

Note: While resize() will grow the capacity if needed, it never shrinks capacity. To shed excess capacity, use squeeze().

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(qsizetype, 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(), reserve(), and squeeze().

void QString::resize(qsizetype newSize, QChar fillChar)

This is an overloaded function.

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

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

[since 6.8] void QString::resizeForOverwrite(qsizetype size)

Sets the size of the string to size characters. If the size of the string grows, the new characters are uninitialized.

The behavior is identical to resize(size).

This function was introduced in Qt 6.8.

See also resize().

QString QString::rightJustified(qsizetype width, QChar fill = u' ', 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().

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

This function returns a section of the string.

This string is treated as a sequence of fields separated by the character, sep. The returned string consists of the fields from position start to position end inclusive. If end is not specified, all fields from position start to the end of the string are included. Fields are numbered 0, 1, 2, etc., counting from the left, and -1, -2, etc., counting from right to left.

The flags argument can be used to affect some aspects of the function's behavior, e.g. whether to be case sensitive, whether to skip empty fields and how to deal with leading and trailing separators; see SectionFlags.

 QString str;
 QString csv = "forename,middlename,surname,phone";
 QString path = "/usr/local/bin/myapp"; // First field is empty
 QString::SectionFlag flag = QString::SectionSkipEmpty;

 str = csv.section(',', 2, 2);   // str == "surname"
 str = path.section('/', 3, 4);  // str == "bin/myapp"
 str = path.section('/', 3, 3, flag); // str == "myapp"

If start or end is negative, we count fields from the right of the string, the right-most field being -1, the one from right-most field being -2, and so on.

 str = csv.section(',', -3, -2);  // str == "middlename,surname"
 str = path.section('/', -1); // str == "myapp"

See also split().

QString QString::section(const QRegularExpression &re, qsizetype start, qsizetype 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.

See also split() and simplified().

QString QString::section(const QString &sep, qsizetype start, qsizetype 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::setNum(int n, int base = 10)

Sets the string to the printed value of n in the specified base, and returns a reference to the string.

The base is 10 by default and must be between 2 and 36.

 QString str;
 str.setNum(1234);       // str == "1234"

The formatting always uses QLocale::C, i.e., English/UnitedStates. To get a localized string representation of a number, use QLocale::toString() with the appropriate locale.

See also number().

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

This is an overloaded function.

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::setNum(short n, int base = 10)

This is an overloaded function.

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

This is an overloaded function.

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

This is an overloaded function.

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

This is an overloaded function.

QString &QString::setNum(double n, char format = 'g', int precision = 6)

This is an overloaded function.

Sets the string to the printed value of n, formatted according to the given format and precision, and returns a reference to the string.

See also number(), QLocale::FloatingPointPrecisionOption, and Number Formats.

QString &QString::setNum(float n, char format = 'g', int precision = 6)

This is an overloaded function.

Sets the string to the printed value of n, formatted according to the given format and precision, and returns a reference to the string.

The formatting always uses QLocale::C, i.e., English/UnitedStates. To get a localized string representation of a number, use QLocale::toString() with the appropriate locale.

See also number().

QString &QString::setRawData(const QChar *unicode, qsizetype 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.

See also fromRawData().

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

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

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

See also unicode() and setUtf16().

QString &QString::setUtf16(const ushort *unicode, qsizetype size)

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

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

Note that unlike fromUtf16(), this function does not consider BOMs and possibly differing byte ordering.

See also utf16() and setUnicode().

void QString::shrink_to_fit()

This function is provided for STL compatibility. It is equivalent to squeeze().

See also squeeze().

QString QString::simplified() const

Returns a string that has whitespace removed from the start and the end, and that has each sequence of internal whitespace replaced with a single space.

Whitespace means any character for which QChar::isSpace() returns true. This includes the ASCII characters '\t', '\n', '\v', '\f', '\r', and ' '.

Example:

 QString str = "  lots\t of\nwhitespace\r\n ";
 str = str.simplified();
 // str == "lots of whitespace";

See also trimmed().

[noexcept] qsizetype QString::size() const

Returns the number of characters in this string.

The last character in the string is at position size() - 1.

Example:

 QString str = "World";
 qsizetype n = str.size();   // n == 5
 str.data()[0];              // returns 'W'
 str.data()[4];              // returns 'd'

See also isEmpty() and resize().

[since 6.8] QString &QString::slice(qsizetype pos, qsizetype n)

Modifies this string to start at position pos, extending for n characters (code points), and returns a reference to this string.

Note: The behavior is undefined if pos < 0, n < 0, or pos + n > size().

 str = "%1%3%2";
 str.arg("Hello").arg(20).arg(50); // returns "Hello500"

 str = "%1%2%3";
 str.arg("Hello").arg(50).arg(20); // returns "Hello5020"

This function was introduced in Qt 6.8.

See also sliced(), first(), last(), chopped(), chop(), and truncate().

[since 6.8] QString &QString::slice(qsizetype pos)

This is an overloaded function.

Modifies this string to start at position pos and extending to its end, and returns a reference to this string.

Note: The behavior is undefined if pos < 0 or pos > size().

This function was introduced in Qt 6.8.

See also sliced(), first(), last(), chopped(), chop(), and truncate().

QStringList QString::split(const QString &sep, Qt::SplitBehavior behavior = Qt::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 Qt::SkipEmptyParts, empty entries don't appear in the result. By default, empty entries are kept.

Example:

 QString str = QStringLiteral("a,,b,c");

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

 QStringList list2 = str.split(u',', Qt::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(QString());
 // 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(u'/');
 // parts: {"", "a", "b", "c", ""}

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

QStringList QString::split(const QRegularExpression &re, Qt::SplitBehavior behavior = Qt::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+"), Qt::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", "." ]

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

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

This is an overloaded function.

void QString::squeeze()

Releases any memory not required to store the character data.

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.

See also reserve() and capacity().

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 (the 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(QChar c, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

This function overloads startsWith().

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

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

This function overloads startsWith().

[noexcept] bool QString::startsWith(QStringView str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

This is an overloaded function.

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

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

See also endsWith().

[noexcept] void QString::swap(QString &other)

Swaps string other with this string. This operation is very fast and never fails.

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 macOS and iOS.

QString QString::toCaseFolded() const

Returns the case folded equivalent of the string. For most Unicode characters this is the same as toLower().

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

[since 6.6] emscripten::val QString::toEcmaString() const

Converts this object to an ECMAScript string.

This function was introduced in Qt 6.6.

See also fromEcmaString().

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

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; otherwise, if the string begins with "0b", base 2 is used; otherwise, 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.

Note: Support for the "0b" prefix was added in Qt 6.4.

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

QByteArray QString::toLatin1() const

Returns a Latin-1 representation of the string as a QByteArray.

The returned byte array is undefined if the string contains non-Latin1 characters. Those characters may be suppressed or replaced with a question mark.

See also fromLatin1(), toUtf8(), toLocal8Bit(), and QStringEncoder.

QByteArray QString::toLocal8Bit() const

Returns the local 8-bit representation of the string as a QByteArray.

On Unix systems this is equivalent to toUtf8(). Note that on Apple systems this function does not take NSString.defaultCStringEncoding or CFStringGetSystemEncoding() into account, as these functions typically return the legacy "Western (Mac OS Roman)" encoding, which should not be used on modern Apple operating systems. On Windows the system's current code page is used.

If this string contains any characters that cannot be encoded in the local 8-bit encoding, the returned byte array is undefined. Those characters may be suppressed or replaced by another.

See also fromLocal8Bit(), toLatin1(), toUtf8(), and QStringEncoder.

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

Returns the string converted to a 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; otherwise, if the string begins with "0b", base 2 is used; otherwise, 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;

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

This function ignores leading and trailing whitespace.

Note: Support for the "0b" prefix was added in Qt 6.4.

See also number(), toULong(), toInt(), 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; otherwise, if the string begins with "0b", base 2 is used; otherwise, 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.

Note: Support for the "0b" prefix was added in Qt 6.4.

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

QString QString::toLower() const

Returns a lowercase copy of the string.

 QString str = "The Qt PROJECT";
 str = str.toLower();        // str == "the qt project"

The case conversion will always happen in the 'C' locale. For locale-dependent case folding use QLocale::toLower()

See also toUpper() and QLocale::toLower().

NSString *QString::toNSString() const

Creates a NSString from a QString.

The NSString is autoreleased.

Note: this function is only available on macOS and iOS.

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; otherwise, if the string begins with "0b", base 2 is used; otherwise, 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.

Note: Support for the "0b" prefix was added in Qt 6.4.

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

std::string QString::toStdString() const

Returns a std::string object with the data contained in this QString. The Unicode data is converted into 8-bit characters using the toUtf8() function.

This method is mostly useful to pass a QString to a function that accepts a std::string object.

See also toLatin1(), toUtf8(), toLocal8Bit(), and QByteArray::toStdString().

std::u16string QString::toStdU16String() const

Returns a std::u16string object with the data contained in this QString. The Unicode data is the same as returned by the utf16() method.

See also utf16(), toStdWString(), and toStdU32String().

std::u32string QString::toStdU32String() const

Returns a std::u32string object with the data contained in this QString. The Unicode data is the same as returned by the toUcs4() method.

See also toUcs4(), toStdWString(), and toStdU16String().

std::wstring QString::toStdWString() const

Returns a std::wstring object with the data contained in this QString. The std::wstring is encoded in UTF-16 on platforms where wchar_t is 2 bytes wide (for example, Windows) and in UTF-32 on platforms where wchar_t is 4 bytes wide (most Unix systems).

This method is mostly useful to pass a QString to a function that accepts a std::wstring object.

See also utf16(), toLatin1(), toUtf8(), toLocal8Bit(), toStdU16String(), and toStdU32String().

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; otherwise, if the string begins with "0b", base 2 is used; otherwise, 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.

Note: Support for the "0b" prefix was added in Qt 6.4.

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

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

Returns the string converted to an unsigned 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; otherwise, if the string begins with "0b", base 2 is used; otherwise, 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;

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

This function ignores leading and trailing whitespace.

Note: Support for the "0b" prefix was added in Qt 6.4.

See also number() 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; otherwise, if the string begins with "0b", base 2 is used; otherwise, 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.

Note: Support for the "0b" prefix was added in Qt 6.4.

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; otherwise, if the string begins with "0b", base 2 is used; otherwise, 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.

Note: Support for the "0b" prefix was added in Qt 6.4.

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

QList<uint> QString::toUcs4() const

Returns a UCS-4/UTF-32 representation of the string as a QList<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 list is not \0'-terminated.

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

QString QString::toUpper() const

Returns an uppercase copy of the string.

 QString str = "TeXt";
 str = str.toUpper();        // str == "TEXT"

The case conversion will always happen in the 'C' locale. For locale-dependent case folding use QLocale::toUpper().

Note: In some cases the uppercase form of a string may be longer than the original.

See also toLower() and QLocale::toLower().

QByteArray QString::toUtf8() const

Returns a UTF-8 representation of the string as a QByteArray.

UTF-8 is a Unicode codec and can represent all characters in a Unicode string like QString.

See also fromUtf8(), toLatin1(), toLocal8Bit(), and QStringEncoder.

qsizetype QString::toWCharArray(wchar_t *array) const

Fills the array with the data contained in this QString object. The array is encoded in UTF-16 on platforms where wchar_t is 2 bytes wide (e.g. windows) and in UCS-4 on platforms where wchar_t is 4 bytes wide (most Unix systems).

array has to be allocated by the caller and contain enough space to hold the complete string (allocating the array with the same length as the string is always sufficient).

This function returns the actual length of the string in array.

Note: This function does not append a null character to the array.

See also utf16(), toUcs4(), toLatin1(), toUtf8(), toLocal8Bit(), toStdWString(), and QStringView::toWCharArray().

QString QString::trimmed() const

Returns a string that has whitespace removed from the start and the end.

Whitespace means any character for which QChar::isSpace() returns true. This includes the ASCII characters '\t', '\n', '\v', '\f', '\r', and ' '.

Example:

 QString str = "  lots\t of\nwhitespace\r\n ";
 str = str.trimmed();
 // str == "lots\t of\nwhitespace"

Unlike simplified(), trimmed() leaves internal whitespace alone.

See also simplified().

void QString::truncate(qsizetype position)

Truncates the string at the given position index.

If the specified position index is beyond the end of the string, nothing happens.

Example:

 QString str = "Vladivostok";
 str.truncate(4);
 // str == "Vlad"

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

See also chop(), resize(), first(), and QStringView::truncate().

const QChar *QString::unicode() const

Returns a Unicode representation of the string. The result remains valid until the string is modified.

Note: The returned string may not be '\0'-terminated. Use size() to determine the length of the array.

See also setUnicode(), utf16(), and fromRawData().

const ushort *QString::utf16() const

Returns the QString as a '\0'-terminated array of unsigned shorts. The result remains valid until the string is modified.

The returned string is in host byte order.

See also setUtf16() and unicode().

[static] QString QString::vasprintf(const char *cformat, va_list ap)

Equivalent method to asprintf(), but takes a va_list ap instead a list of variable arguments. See the asprintf() documentation for an explanation of cformat.

This method does not call the va_end macro, the caller is responsible to call va_end on ap.

See also asprintf().

[noexcept, since 6.7] std::u16string_view QString::operator std::u16string_view() const

Converts this QString object to a std::u16string_view object.

This function was introduced in Qt 6.7.

QString &QString::operator+=(const QString &other)

Appends the string other onto the end of this string and returns a reference to this string.

Example:

 QString x = "free";
 QString y = "dom";
 x += y;
 // x == "freedom"

This operation 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 append() and prepend().

QString &QString::operator+=(QChar ch)

This function overloads operator+=().

Appends the character ch to the string.

QString &QString::operator+=(QLatin1StringView str)

This function overloads operator+=().

Appends the Latin-1 string viewed by str to this string.

[since 6.0] QString &QString::operator+=(QStringView str)

This function overloads operator+=().

Appends the string view str to this string.

This function was introduced in Qt 6.0.

[since 6.5] QString &QString::operator+=(QUtf8StringView str)

This function overloads operator+=().

Appends the UTF-8 string view str to this string.

This function was introduced in Qt 6.5.

QString &QString::operator+=(const QByteArray &ba)

This function overloads operator+=().

Appends the byte array ba to this string. The byte array is converted to Unicode using the fromUtf8() function. If any NUL characters ('\0') are embedded in the ba byte array, they will be included in the transformation.

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.

QString &QString::operator+=(const char *str)

This function overloads operator+=().

Appends the string str to this string. The const char pointer is converted to Unicode using the fromUtf8() 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.

[noexcept] QString &QString::operator=(QString &&other)

Move-assigns other to this QString instance.

[noexcept] QString &QString::operator=(const QString &other)

Assigns other to this string and returns a reference to this string.

QString &QString::operator=(QChar ch)

This function overloads operator=().

Sets the string to contain the single character ch.

QString &QString::operator=(QLatin1StringView str)

This function overloads operator=().

Assigns the Latin-1 string viewed by str to this string.

QString &QString::operator=(const QByteArray &ba)

This function overloads operator=().

Assigns ba to this string. The byte array is converted to Unicode using the fromUtf8() function.

You can disable this operator 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.

QString &QString::operator=(const char *str)

This function overloads operator=().

Assigns str to this string. The const char pointer is converted to Unicode using the fromUtf8() function.

You can disable this operator by defining QT_NO_CAST_FROM_ASCII or QT_RESTRICTED_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.

QChar &QString::operator[](qsizetype position)

Returns the character at the specified position in the string as a modifiable reference.

Example:

 QString str;

 if (str[0] == QChar('?'))
     str[0] = QChar('_');

See also at().

const QChar QString::operator[](qsizetype position) const

This function overloads operator[]().

Related Non-Members

QString operator+(QString &&s1, const QString &s2)

QString operator+(const QString &s1, const QString &s2)

Returns a string which is the result of concatenating s1 and s2.

[since 6.1] template <typename T> qsizetype erase(QString &s, const T &t)

Removes all elements that compare equal to t from the string s. Returns the number of elements removed, if any.

This function was introduced in Qt 6.1.

See also erase_if.

[since 6.1] template <typename Predicate> qsizetype erase_if(QString &s, Predicate pred)

Removes all elements for which the predicate pred returns true from the string s. Returns the number of elements removed, if any.

This function was introduced in Qt 6.1.

See also erase.

[noexcept] bool operator!=(const QByteArray &lhs, const QString &rhs)

Returns true if byte array lhs is not equal to the UTF-8 encoding of rhs; otherwise returns false.

The comparison is case sensitive.

You can disable this operator by defining QT_NO_CAST_FROM_ASCII when you compile your applications. You then need to call QString::fromUtf8(), QString::fromLatin1(), or QString::fromLocal8Bit() explicitly if you want to convert the byte array to a QString before doing the comparison.

[noexcept] bool operator!=(const QString &lhs, const QString &rhs)

Returns true if string lhs is not equal to string rhs; otherwise returns false.

See also Comparing Strings.

[noexcept] bool operator!=(const char *const &lhs, const QString &rhs)

Returns true if lhs is not equal to rhs; otherwise returns false.

For lhs != 0, this is equivalent to compare( lhs, rhs ) != 0. Note that no string is equal to lhs being 0.

[noexcept] bool operator!=(const QString &lhs, const QByteArray &rhs)

This function overloads operator!=().

The rhs byte array is converted to a QUtf8StringView. If any NUL characters ('\0') are embedded in the byte array, they will be included in the transformation.

You can disable this operator 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.

[noexcept] bool operator!=(const QString &lhs, const QLatin1StringView &rhs)

Returns true if string lhs is not equal to string rhs. Otherwise returns false.

This function overloads operator!=().

[noexcept] bool operator!=(const QString &lhs, const char *const &rhs)

This function overloads operator!=().

The rhs const char pointer is converted to a QUtf8StringView.

You can disable this operator 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.

QString operator+(const QString &s1, const char *s2)

Returns a string which is the result of concatenating s1 and s2 (s2 is converted to Unicode using the QString::fromUtf8() function).

See also QString::fromUtf8().

QString operator+(const char *s1, const QString &s2)

Returns a string which is the result of concatenating s1 and s2 (s1 is converted to Unicode using the QString::fromUtf8() function).

See also QString::fromUtf8().

[noexcept] bool operator<(const QByteArray &lhs, const QString &rhs)

Returns true if byte array lhs is lexically less than the UTF-8 encoding of rhs; otherwise returns false.

The comparison is case sensitive.

You can disable this operator by defining QT_NO_CAST_FROM_ASCII when you compile your applications. You then need to call QString::fromUtf8(), QString::fromLatin1(), or QString::fromLocal8Bit() explicitly if you want to convert the byte array to a QString before doing the comparison.

[noexcept] bool operator<(const char *const &lhs, const QString &rhs)

Returns true if lhs is lexically less than rhs; otherwise returns false. For lhs != 0, this is equivalent to compare(lhs, rhs) < 0.

See also Comparing Strings.

[noexcept] bool operator<(const QLatin1StringView &lhs, const QString &rhs)

This function overloads operator<().

Returns true if lhs is lexically less than rhs; otherwise returns false.

[noexcept] bool operator<(const QString &lhs, const QByteArray &rhs)

This function overloads operator<().

The rhs byte array is converted to a QUtf8StringView. If any NUL characters ('\0') are embedded in the byte array, they will be included in the transformation.

You can disable this operator 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.

[noexcept] bool operator<(const QString &lhs, const QLatin1StringView &rhs)

This function overloads operator<().

Returns true if lhs is lexically less than rhs; otherwise returns false.

[noexcept] bool operator<(const QString &lhs, const QString &rhs)

This function overloads operator<().

Returns true if string lhs is lexically less than string rhs; otherwise returns false.

See also Comparing Strings.

[noexcept] bool operator<(const QString &lhs, const char *const &rhs)

Returns true if string lhs is lexically less than string rhs. Otherwise returns false.

This function overloads operator<().

The rhs const char pointer is converted to a QUtf8StringView.

You can disable this operator 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.

QDataStream &operator<<(QDataStream &stream, const QString &string)

Writes the given string to the specified stream.

See also Serializing Qt Data Types.

[noexcept] bool operator<=(const QByteArray &lhs, const QString &rhs)

Returns true if byte array lhs is lexically less than or equal to the UTF-8 encoding of rhs; otherwise returns false.

The comparison is case sensitive.

You can disable this operator by defining QT_NO_CAST_FROM_ASCII when you compile your applications. You then need to call QString::fromUtf8(), QString::fromLatin1(), or QString::fromLocal8Bit() explicitly if you want to convert the byte array to a QString before doing the comparison.

[noexcept] bool operator<=(const QString &lhs, const QString &rhs)

Returns true if string lhs is lexically less than or equal to string rhs; otherwise returns false.

See also Comparing Strings.

[noexcept] bool operator<=(const char *const &lhs, const QString &rhs)

Returns true if lhs is lexically less than or equal to rhs; otherwise returns false. For lhs != 0, this is equivalent to compare(lhs, rhs) <= 0.

See also Comparing Strings.

[noexcept] bool operator<=(const QLatin1StringView &lhs, const QString &rhs)

This function overloads operator<=().

Returns true if lhs is lexically less than or equal to rhs; otherwise returns false.

[noexcept] bool operator<=(const QString &lhs, const QByteArray &rhs)

This function overloads operator<=().

The rhs byte array is converted to a QUtf8StringView. If any NUL characters ('\0') are embedded in the byte array, they will be included in the transformation.

You can disable this operator 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.

[noexcept] bool operator<=(const QString &lhs, const QLatin1StringView &rhs)

This function overloads operator<=().

Returns true if lhs is lexically less than or equal to rhs; otherwise returns false.

[noexcept] bool operator<=(const QString &lhs, const char *const &rhs)

This function overloads operator<=().

The rhs const char pointer is converted to a QUtf8StringView.

You can disable this operator 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.

[noexcept] bool operator==(const QByteArray &lhs, const QString &rhs)

Returns true if byte array lhs is equal to the UTF-8 encoding of rhs; otherwise returns false.

The comparison is case sensitive.

You can disable this operator by defining QT_NO_CAST_FROM_ASCII when you compile your applications. You then need to call QString::fromUtf8(), QString::fromLatin1(), or QString::fromLocal8Bit() explicitly if you want to convert the byte array to a QString before doing the comparison.

[noexcept] bool operator==(const QLatin1StringView &lhs, const QString &rhs)

This function overloads operator==().

Returns true if lhs is equal to rhs; otherwise returns false.

[noexcept] bool operator==(const QString &lhs, const QByteArray &rhs)

This function overloads operator==().

The rhs byte array is converted to a QUtf8StringView.

You can disable this operator 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.

Returns true if string lhs is lexically equal to rhs. Otherwise returns false.

[noexcept] bool operator==(const QString &lhs, const QLatin1StringView &rhs)

This function overloads operator==().

Returns true if lhs is equal to rhs; otherwise returns false.

[noexcept] bool operator==(const QString &lhs, const QString &rhs)

This function overloads operator==().

Returns true if string lhs is equal to string rhs; otherwise returns false.

Note: This function treats null strings the same as empty strings, for more details see Distinction Between Null and Empty Strings.

See also Comparing Strings.

[noexcept] bool operator==(const QString &lhs, const char *const &rhs)

This function overloads operator==().

The rhs const char pointer is converted to a QUtf8StringView.

You can disable this operator 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.

[noexcept] bool operator==(const char *const &lhs, const QString &rhs)

This function overloads operator==().

Returns true if lhs is equal to rhs; otherwise returns false. Note that no string is equal to lhs being 0.

Equivalent to lhs != 0 && compare(lhs, rhs) == 0.

[noexcept] bool operator>(const QByteArray &lhs, const QString &rhs)

Returns true if byte array lhs is lexically greater than the UTF-8 encoding of rhs; otherwise returns false.

The comparison is case sensitive.

You can disable this operator by defining QT_NO_CAST_FROM_ASCII when you compile your applications. You then need to call QString::fromUtf8(), QString::fromLatin1(), or QString::fromLocal8Bit() explicitly if you want to convert the byte array to a QString before doing the comparison.

[noexcept] bool operator>(const QString &lhs, const QString &rhs)

Returns true if string lhs is lexically greater than string rhs; otherwise returns false.

See also Comparing Strings.

[noexcept] bool operator>(const char *const &lhs, const QString &rhs)

Returns true if lhs is lexically greater than rhs; otherwise returns false. Equivalent to compare(lhs, rhs) > 0.

See also Comparing Strings.

[noexcept] bool operator>(const QLatin1StringView &lhs, const QString &rhs)

This function overloads operator>().

Returns true if lhs is lexically greater than rhs; otherwise returns false.

[noexcept] bool operator>(const QString &lhs, const QByteArray &rhs)

This function overloads operator>().

The rhs byte array is converted to a QUtf8StringView. If any NUL characters ('\0') are embedded in the byte array, they will be included in the transformation.

You can disable this operator 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.

[noexcept] bool operator>(const QString &lhs, const QLatin1StringView &rhs)

This function overloads operator>().

Returns true if lhs is lexically greater than rhs; otherwise returns false.

[noexcept] bool operator>(const QString &lhs, const char *const &rhs)

This function overloads operator>().

The rhs const char pointer is converted to a QUtf8StringView.

You can disable this operator 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.

[noexcept] bool operator>=(const QByteArray &lhs, const QString &rhs)

Returns true if byte array lhs is greater than or equal to the UTF-8 encoding of rhs; otherwise returns false.

The comparison is case sensitive.

You can disable this operator by defining QT_NO_CAST_FROM_ASCII when you compile your applications. You then need to call QString::fromUtf8(), QString::fromLatin1(), or QString::fromLocal8Bit() explicitly if you want to convert the byte array to a QString before doing the comparison.

[noexcept] bool operator>=(const QString &lhs, const QString &rhs)

Returns true if string lhs is lexically greater than or equal to string rhs; otherwise returns false.

See also Comparing Strings.

[noexcept] bool operator>=(const char *const &lhs, const QString &rhs)

Returns true if lhs is lexically greater than or equal to rhs; otherwise returns false. For lhs != 0, this is equivalent to compare(lhs, rhs) >= 0.

See also Comparing Strings.

[noexcept] bool operator>=(const QLatin1StringView &lhs, const QString &rhs)

This function overloads operator>=().

Returns true if lhs is lexically greater than or equal to rhs; otherwise returns false.

[noexcept] bool operator>=(const QString &lhs, const QByteArray &rhs)

This function overloads operator>=().

The rhs byte array is converted to a QUtf8StringView. If any NUL characters ('\0') are embedded in the byte array, they will be included in the transformation.

You can disable this operator 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.

[noexcept] bool operator>=(const QString &lhs, const QLatin1StringView &rhs)

This function overloads operator>=().

Returns true if lhs is lexically greater than or equal to rhs; otherwise returns false.

[noexcept] bool operator>=(const QString &lhs, const char *const &rhs)

This function overloads operator>=().

The rhs const char pointer is converted to a QUtf8StringView.

You can disable this operator 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.

QDataStream &operator>>(QDataStream &stream, QString &string)

Reads a string from the specified stream into the given string.

See also Serializing Qt Data Types.

Macro Documentation

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: QLatin1StringView can still be more efficient than QStringLiteral when the string is passed to a function that has an overload taking QLatin1StringView and this overload avoids conversion to QString. For instance, QString::operator==() can compare to a QLatin1StringView directly:

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

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.

QT_NO_CAST_FROM_ASCII

Disables automatic conversions from 8-bit strings (char *) to Unicode QStrings, as well as from 8-bit char types (char and unsigned char) to QChar.

See also QT_NO_CAST_TO_ASCII, QT_RESTRICTED_CAST_FROM_ASCII, and QT_NO_CAST_FROM_BYTEARRAY.

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.

QT_RESTRICTED_CAST_FROM_ASCII

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. This gives 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, QLatin1StringView 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.

const char *qPrintable(const QString &str)

Returns str as a const char *. This is equivalent to str.toLocal8Bit().constData().

The char pointer will be invalid after the statement in which qPrintable() is used. This is because the array returned by QString::toLocal8Bit() will fall out of scope.

Note: qDebug(), qInfo(), qWarning(), qCritical(), qFatal() expect %s arguments to be UTF-8 encoded, while qPrintable() converts to local 8-bit encoding. Therefore qUtf8Printable() should be used for logging strings instead of qPrintable().

See also qUtf8Printable().

const wchar_t *qUtf16Printable(const QString &str)

Returns str as a const ushort *, but cast to a const wchar_t * to avoid warnings. This is equivalent to str.utf16() plus some casting.

The only useful thing you can do with the return value of this macro is to pass it to QString::asprintf() for use in a %ls conversion. In particular, the return value is not a valid const wchar_t*!

In general, the pointer will be invalid after the statement in which qUtf16Printable() is used. This is because the pointer may have been obtained from a temporary expression, which will fall out of scope.

Example:

 qWarning("%ls: %ls", qUtf16Printable(key), qUtf16Printable(value));

See also qPrintable(), qDebug(), qInfo(), qWarning(), qCritical(), and qFatal().

const char *qUtf8Printable(const QString &str)

Returns str as a const char *. This is equivalent to str.toUtf8().constData().

The char pointer will be invalid after the statement in which qUtf8Printable() is used. This is because the array returned by QString::toUtf8() will fall out of scope.

Example:

 qWarning("%s: %s", qUtf8Printable(key), qUtf8Printable(value));

See also qPrintable(), qDebug(), qInfo(), qWarning(), qCritical(), and qFatal().