Viadeo Twitter Google Bookmarks ! Facebook Digg del.icio.us MySpace Yahoo MyWeb Blinklist Netvouz Reddit Simpy StumbleUpon Bookmarks Windows Live Favorites 
Logo Documentation Qt ·  Page d'accueil  ·  Toutes les classes  ·  Classes principales  ·  Annotées  ·  Classes groupées  ·  Modules  ·  Fonctions  · 

QString Class Reference
[QtCore module]

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

#include <QString>

Inherited by QConstString.

Note: All the functions in this class are reentrant.

Public Types

  • class Null
  • enum NormalizationForm { NormalizationForm_D, NormalizationForm_C, NormalizationForm_KD, NormalizationForm_KC }
  • enum SectionFlag { SectionDefault, SectionSkipEmpty, SectionIncludeLeadingSep, SectionIncludeTrailingSep, SectionCaseInsensitiveSeps }
  • enum SplitBehavior { KeepEmptyParts, SkipEmptyParts }

Public Functions

  • QString ( const QChar * unicode, int size )
  • QString ( QChar ch )
  • QString ( int size, QChar ch )
  • QString ( const QLatin1String & str )
  • QString ( const QString & other )
  • QString ( const char * str )
  • QString ( const QByteArray & ba )
  • QString & append ( const QString & str )
  • QString & append ( const QLatin1String & str )
  • QString & append ( const QByteArray & ba )
  • QString & append ( const char * str )
  • QString & append ( QChar ch )
  • QString arg ( const QString & a, int fieldWidth = 0, const QChar & fillChar = QLatin1Char( ' ' ) ) const
  • QString arg ( const QString & a1, const QString & a2 ) const
  • QString arg ( const QString & a1, const QString & a2, const QString & a3 ) const
  • QString arg ( const QString & a1, const QString & a2, const QString & a3, const QString & a4 ) const
  • QString arg ( int a, int fieldWidth = 0, int base = 10, const QChar & fillChar = QLatin1Char( ' ' ) ) const
  • QString arg ( uint a, int fieldWidth = 0, int base = 10, const QChar & fillChar = QLatin1Char( ' ' ) ) const
  • QString arg ( long a, int fieldWidth = 0, int base = 10, const QChar & fillChar = QLatin1Char( ' ' ) ) const
  • QString arg ( ulong a, int fieldWidth = 0, int base = 10, const QChar & fillChar = QLatin1Char( ' ' ) ) const
  • QString arg ( qlonglong a, int fieldWidth = 0, int base = 10, const QChar & fillChar = QLatin1Char( ' ' ) ) const
  • QString arg ( qulonglong a, int fieldWidth = 0, int base = 10, const QChar & fillChar = QLatin1Char( ' ' ) ) const
  • QString arg ( short a, int fieldWidth = 0, int base = 10, const QChar & fillChar = QLatin1Char( ' ' ) ) const
  • QString arg ( ushort a, int fieldWidth = 0, int base = 10, const QChar & fillChar = QLatin1Char( ' ' ) ) const
  • QString arg ( QChar a, int fieldWidth = 0, const QChar & fillChar = QLatin1Char( ' ' ) ) const
  • QString arg ( char a, int fieldWidth = 0, const QChar & fillChar = QLatin1Char( ' ' ) ) const
  • QString arg ( double a, int fieldWidth = 0, char fmt = 'g', int prec = -1, const QChar & fillChar = QLatin1Char( ' ' ) ) const
  • const QChar at ( int i ) const
  • int capacity () const
  • void chop ( int n )
  • void clear ()
  • int compare ( const QString & other ) const
  • const QChar * constData () const
  • bool contains ( const QString & str, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
  • bool contains ( QChar ch, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
  • bool contains ( const QRegExp & rx ) const
  • int count ( const QString & str, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
  • int count ( QChar ch, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
  • int count ( const QRegExp & rx ) const
  • int count () const
  • QChar * data ()
  • const QChar * data () const
  • bool endsWith ( const QString & s, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
  • bool endsWith ( const QLatin1String & s, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
  • bool endsWith ( const QChar & c, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
  • QString & fill ( QChar ch, int size = -1 )
  • int indexOf ( const QString & str, int from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
  • int indexOf ( QChar ch, int from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
  • int indexOf ( const QRegExp & rx, int from = 0 ) const
  • QString & insert ( int i, const QString & str )
  • QString & insert ( int i, const QLatin1String & str )
  • QString & insert ( int i, const QChar * unicode, int size )
  • QString & insert ( int i, QChar ch )
  • bool isEmpty () const
  • bool isNull () const
  • int lastIndexOf ( const QString & str, int from = -1, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
  • int lastIndexOf ( QChar ch, int from = -1, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
  • int lastIndexOf ( const QRegExp & rx, int from = -1 ) const
  • QString left ( int len ) const
  • QString leftJustified ( int width, QChar fill = QLatin1Char( ' ' ), bool truncate = false ) const
  • int length () const
  • int localeAwareCompare ( const QString & other ) const
  • QString mid ( int i, int len = -1 ) const
  • QString normalized ( NormalizationForm form ) const
  • QString normalized ( NormalizationForm form, QChar::UnicodeVersion version ) const
  • QString & prepend ( const QString & str )
  • QString & prepend ( const QLatin1String & str )
  • QString & prepend ( const QByteArray & ba )
  • QString & prepend ( const char * str )
  • QString & prepend ( QChar ch )
  • void push_back ( const QString & other )
  • void push_back ( QChar ch )
  • void push_front ( const QString & other )
  • void push_front ( QChar ch )
  • QString & remove ( int pos, int len )
  • QString & remove ( const QString & str, Qt::CaseSensitivity cs = Qt::CaseSensitive )
  • QString & remove ( QChar ch, Qt::CaseSensitivity cs = Qt::CaseSensitive )
  • QString & remove ( const QRegExp & rx )
  • QString & replace ( int pos, int len, const QString & after )
  • QString & replace ( int pos, int len, const QChar * unicode, int size )
  • QString & replace ( int pos, int len, QChar after )
  • QString & replace ( const QString & before, const QString & after, Qt::CaseSensitivity cs = Qt::CaseSensitive )
  • QString & replace ( QChar ch, const QString & after, Qt::CaseSensitivity cs = Qt::CaseSensitive )
  • QString & replace ( QChar before, QChar after, Qt::CaseSensitivity cs = Qt::CaseSensitive )
  • QString & replace ( const QRegExp & rx, const QString & after )
  • void reserve ( int size )
  • void resize ( int size )
  • QString right ( int len ) const
  • QString rightJustified ( int width, QChar fill = QLatin1Char( ' ' ), bool truncate = false ) const
  • QString section ( QChar sep, int start, int end = -1, SectionFlags flags = SectionDefault ) const
  • QString section ( const QString & sep, int start, int end = -1, SectionFlags flags = SectionDefault ) const
  • QString section ( const QRegExp & reg, int start, int end = -1, SectionFlags flags = SectionDefault ) const
  • QString & setNum ( int n, int base = 10 )
  • QString & setNum ( uint n, int base = 10 )
  • QString & setNum ( long n, int base = 10 )
  • QString & setNum ( ulong 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 ( ushort n, int base = 10 )
  • QString & setNum ( double n, char f = 'g', int prec = 6 )
  • QString & setNum ( float n, char f = 'g', int prec = 6 )
  • QString & setUnicode ( const QChar * unicode, int size )
  • QString & setUtf16 ( const ushort * unicode, int size )
  • QString simplified () const
  • int size () const
  • QStringList split ( const QString & sep, SplitBehavior behavior = KeepEmptyParts, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
  • QStringList split ( const QChar & sep, SplitBehavior behavior = KeepEmptyParts, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
  • QStringList split ( const QRegExp & rx, SplitBehavior behavior = KeepEmptyParts ) const
  • QString & sprintf ( const char * cformat, ... )
  • void squeeze ()
  • bool startsWith ( const QString & s, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
  • bool startsWith ( const QLatin1String & s, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
  • bool startsWith ( const QChar & c, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
  • QByteArray toAscii () const
  • double toDouble ( bool * ok = 0 ) const
  • float toFloat ( bool * ok = 0 ) const
  • int toInt ( bool * ok = 0, int base = 10 ) const
  • QByteArray toLatin1 () const
  • QByteArray toLocal8Bit () const
  • long toLong ( bool * ok = 0, int base = 10 ) const
  • qlonglong toLongLong ( bool * ok = 0, int base = 10 ) const
  • QString toLower () const
  • short toShort ( bool * ok = 0, int base = 10 ) const
  • std::string toStdString () const
  • std::wstring toStdWString () const
  • uint toUInt ( bool * ok = 0, int base = 10 ) const
  • ulong toULong ( bool * ok = 0, int base = 10 ) const
  • qulonglong toULongLong ( bool * ok = 0, int base = 10 ) const
  • ushort toUShort ( bool * ok = 0, int base = 10 ) const
  • QString toUpper () const
  • QByteArray toUtf8 () const
  • QString trimmed () const
  • void truncate ( int pos )
  • const QChar * unicode () const
  • const ushort * utf16 () const
  • QString & vsprintf ( const char * cformat, va_list ap )
  • bool operator!= ( const QString & other ) const
  • bool operator!= ( const QLatin1String & other ) const
  • bool operator!= ( const QByteArray & other ) const
  • bool operator!= ( const char * other ) const
  • QString & operator+= ( const QString & other )
  • QString & operator+= ( const QLatin1String & str )
  • QString & operator+= ( const QByteArray & ba )
  • QString & operator+= ( const char * str )
  • QString & operator+= ( char ch )
  • QString & operator+= ( QChar ch )
  • bool operator< ( const QString & other ) const
  • bool operator< ( const QLatin1String & other ) const
  • bool operator< ( const QByteArray & other ) const
  • bool operator< ( const char * other ) const
  • bool operator<= ( const QString & other ) const
  • bool operator<= ( const QLatin1String & other ) const
  • bool operator<= ( const QByteArray & other ) const
  • bool operator<= ( const char * other ) const
  • QString & operator= ( const QString & other )
  • QString & operator= ( const QLatin1String & str )
  • QString & operator= ( const QByteArray & ba )
  • QString & operator= ( const char * str )
  • QString & operator= ( char ch )
  • QString & operator= ( QChar ch )
  • bool operator== ( const QString & other ) const
  • bool operator== ( const QLatin1String & other ) const
  • bool operator== ( const QByteArray & other ) const
  • bool operator== ( const char * other ) const
  • bool operator> ( const QString & other ) const
  • bool operator> ( const QLatin1String & other ) const
  • bool operator> ( const QByteArray & other ) const
  • bool operator> ( const char * other ) const
  • bool operator>= ( const QString & other ) const
  • bool operator>= ( const QLatin1String & other ) const
  • bool operator>= ( const QByteArray & other ) const
  • bool operator>= ( const char * other ) const
  • QCharRef operator[] ( int i )
  • const QChar operator[] ( int i ) const
  • QCharRef operator[] ( uint i )
  • const QChar operator[] ( uint i ) const

Static Public Members

  • int compare ( const QString & s1, const QString & s2 )
  • QString fromAscii ( const char * str, int size = -1 )
  • QString fromLatin1 ( const char * str, int size = -1 )
  • QString fromLocal8Bit ( const char * str, int size = -1 )
  • QString fromRawData ( const QChar * unicode, int size )
  • QString fromStdString ( const std::string & str )
  • QString fromStdWString ( const std::wstring & str )
  • QString fromUtf8 ( const char * str, int size = -1 )
  • QString fromUtf16 ( const ushort * unicode, int size = -1 )
  • int localeAwareCompare ( const QString & s1, const QString & s2 )
  • QString number ( long n, int base = 10 )
  • QString number ( ulong n, int base = 10 )
  • QString number ( int n, int base = 10 )
  • QString number ( uint n, int base = 10 )
  • QString number ( qlonglong n, int base = 10 )
  • QString number ( qulonglong n, int base = 10 )
  • QString number ( double n, char f = 'g', int prec = 6 )

Related Non-Members

  • bool operator!= ( const char * s1, const QString & s2 )
  • const QString operator+ ( const QString & s1, const QString & s2 )
  • const QString operator+ ( const QString & s1, const char * s2 )
  • const QString operator+ ( const char * s1, const QString & s2 )
  • const QString operator+ ( const QString & s, char ch )
  • const QString operator+ ( char ch, const QString & s )
  • bool operator< ( const char * s1, const QString & s2 )
  • QDataStream & operator<< ( QDataStream & out, const QString & str )
  • bool operator<= ( const char * s1, const QString & s2 )
  • bool operator== ( const char * s1, const QString & s2 )
  • bool operator> ( const char * s1, const QString & s2 )
  • bool operator>= ( const char * s1, const QString & s2 )
  • QDataStream & operator>> ( QDataStream & in, QString & str )

Detailed Description

The QString class provides a Unicode character string.

QString stores a string of 16-bit QChars, where each QChar stores one Unicode 4.0 character. Unicode is an international standard that supports most of the writing systems in use today. It is a superset of ASCII and Latin-1 (ISO 8859-1), and all the ASCII/Latin-1 characters are available at the same code positions.

Behind the scenes, QString uses implicit sharing (copy-on-write) to reduce memory usage and to avoid the needless copying of data. This also helps reduce the inherent overhead of storing 16-bit characters instead of 8-bit characters.

In addition to QString, Qt also provides the QByteArray class to store raw bytes and traditional 8-bit '\0'-terminated strings. For most purposes, QString is the class you want to use. It is used throughout the Qt API, and the Unicode support ensures that your applications will be easy to translate if you want to expand your application's market at some point. The two main cases where QByteArray is appropriate are when you need to store raw binary data, and when memory conservation is critical (e.g. with Qtopia Core).

One way to initialize a QString is simply to pass a const char * to its constructor. For example, the following code creates a QString of size 5 containing the data "Hello":

    QString str = "Hello";

QString converts the const char * data into Unicode using fromAscii(). By default, fromAscii() treats character above 128 as Latin-1 characters, but this can be changed by calling QTextCodec::setCodecForCStrings().

In all of the QString methods that take const char * parameters, the const char * is interpreted as a classic C-style '\0'-terminated string. It is legal for the const char * parameter to be 0.

You can also provide string data as an array of QChars:

    static const QChar data[4] = { 0x0055, 0x006e, 0x10e3, 0x03a3 };
    QString str(data, 4);

QString makes a deep copy of the QChar data, so you can modify it later without experiencing side effects. (If for performance reasons you don't want to take a deep copy of the character data, use QString::fromRawData() instead.)

Another approach is to set the size of the string using resize() and to initialize the data character per character. QString uses 0-based indexes, just like C++ arrays. To access the character at a particular index position, you can use operator[](). On non-const strings, operator[]() returns a reference to a character that can be used on the left side of an assignment. For example:

    QString str;
    str.resize(4);
    str[0] = QChar('U');
    str[1] = QChar('n');
    str[2] = QChar(0x10e3);
    str[3] = QChar(0x03a3);

For read-only access, an alternative syntax is to use at():

    for (int i = 0; i < str.size(); ++i) {
        if (str.at(i) >= QChar('a') && str.at(i) <= QChar('f'))
            qDebug() << "Found character in range [a-f]";
    }

at() can be faster than operator[](), because it never causes a deep copy to occur.

To extract several characters at a time, use left(), right(), or mid().

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 resize(), newly allocated characters have undefined values. To set all the characters in the string to a particular value, call fill().

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:

    if (str == "auto" || str == "extern"
            || str == "static" || str == "register") {
        ...
    }

You can also pass string literals to functions that take QStrings and the QString(const char *) constructor will be invoked. Similarily, you can pass a QString to a function that takes a const char * using the qPrintable() macro which returns the given QString as a const char *. This is equivalent to calling <QString>.toAscii().constData().

QString provides the following basic functions for modifying the character data: append(), prepend(), insert(), replace(), and remove(). For example:

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

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

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

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

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

If you want to see if a QString starts or ends with a particular substring use startsWith() or endsWith(). If you simply want to check whether a QString contains a particular character or substring, use contains(). If you want to find out how many times a particular character or substring occurs in the string, use count().

QString provides many functions for converting numbers into strings and strings into numbers. See the arg() functions, the setNum() functions, the number() static functions, and the toInt(), toDouble(), and similar functions.

To get an upper- or lowercase version of a string use toUpper() or toLower().

If you want to replace all occurrences of a particular substring with another, use one of the two-parameter replace() overloads.

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

Lists of strings are handled by the QStringList class. You can split a string into a list of strings using split(), and join a list of strings into a single string with an optional separator using QStringList::join(). You can obtain a list of strings from a string list that contain a particular substring or that match a particular QRegExp using QStringList::find().

If you are building a QString gradually and know in advance approximately how many characters the QString will contain, you can call reserve(), asking QString to preallocate a certain amount of memory. You can also call capacity() to find out how much memory QString actually allocated.

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.

Conversions between 8-bit strings and Unicode strings

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

  • toAscii() returns an ASCII encoded 8-bit string.
  • 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 ASCII that supports the entire Unicode character set through multibyte sequences.
  • toLocal8Bit() returns an 8-bit string using the system's local encoding.

To convert from one of these encodings, QString provides fromAscii(), fromLatin1(), fromUtf8(), and fromLocal8Bit(). Other encodings are supported through QTextCodec.

As mentioned above, QString provides a lot of functions and operators that make it easy to interoperate with const char * strings. This functionaly is a double-edged sword: It makes QString more convenient to use if all strings are ASCII or Latin-1, but there is always the risk that an implicit conversion from or to const char * is done using the wrong 8-bit encoding. To minimize these risks, you can turn off these implicit conversions by defining these two preprocessor symbols:

  • QT_NO_CAST_FROM_ASCII disables automatic conversions from ASCII to Unicode.
  • QT_NO_CAST_TO_ASCII disables automatic conversion from QString to ASCII.

One way to define these prepocessor symbols globally for your application is to add the following entry to your qmake project file:

    DEFINES += QT_NO_CAST_FROM_ASCII \
               QT_NO_CAST_TO_ASCII

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

    QString url = QLatin1String("http://www.unicode.org/");

Similarly, you must call toAscii(), toLatin1(), toUtf8(), or toLocal8Bit() explicitly to convert the QString to an 8-bit string. (Other encodings are supported through QTextCodec.)

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 boolToString(bool b)
    {
        QString result;
        if (b)
            result = "True";
        else
            result = "False";
        return result;
    }

The variable, result, is a normal variable allocated on the stack. When return is called, because we're returning by value, The copy constructor is called and a copy of the string is returned. (No actual copying takes place thanks to the implicit sharing.)

Distinction between null and empty strings

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

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

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

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

All functions except isNull() treat null strings the same as empty strings. For example, toAscii().constData() returns a pointer to a '\0' character for a null string (not a null pointer), and QString() compares equal to QString(""). We recommend that you always use isEmpty() and avoid isNull().

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


Member Type Documentation

enum QString::NormalizationForm

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

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

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

See also section().

enum QString::SplitBehavior

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

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

See also split().


Member Function Documentation

QString::QString ()

Constructs a null string. Null strings are also empty.

See also isEmpty().

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

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

QString makes a deep copy of the string data.

QString::QString ( QChar ch )

Constructs a string of size 1 containing the character ch.

QString::QString ( int size, QChar ch )

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

See also fill().

QString::QString ( const QLatin1String & str )

Constructs a copy of the Latin-1 string str.

See also fromLatin1().

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

QString::QString ( const char * str )

Constructs a string initialized with the ASCII string str. str is converted to Unicode using fromAscii().

You can disable this constructor by defining QT_NO_CAST_FROM_ASCII when you compile your applications. This can be useful if you want to ensure that all user-visible strings go through QObject::tr(), for example.

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

QString::QString ( const QByteArray & ba )

Constructs a string initialized with the byte array ba. ba is converted to Unicode using fromAscii(). Stops copying at the first 0 character, otherwise copies the entire byte array.

You can disable this constructor by defining QT_NO_CAST_FROM_ASCII when you compile your applications. This can be useful if you want to ensure that all user-visible strings go through QObject::tr(), for example.

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 insert(size(), str).

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 operator+=(), prepend(), and insert().

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

This is an overloaded member function, provided for convenience.

Appends the Latin-1 string str to this string.

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

This is an overloaded member function, provided for convenience.

Appends the byte array ba to this string. ba is converted to Unicode using fromAscii().

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 is an overloaded member function, provided for convenience.

Appends the string str to this string. str is converted to Unicode using fromAscii().

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 ( QChar ch )

This is an overloaded member function, provided for convenience.

Appends the character ch to this string.

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

This function returns a copy of this string where a replaces the lowest numbered occurrence of %1, %2, ..., %99.

The fieldWidth value specifies the minimum amount of space that a is padded to and filled with the character fillChar. A positive value will produce right-aligned text, whereas a negative value will produce left-aligned text.

The following example shows how we could create a 'status' string when processing a list of files:

    QString status = QString("Processing file %1 of %2: %3")
                        .arg(i)         // current file's number
                        .arg(total)     // number of files to process
                        .arg(fileName); // current file's name

It is generally fine to use file names and numbers as we have done in the example above. But note that using arg() to construct natural language sentences does not usually translate well into other languages because sentence structure and word order often differ between languages.

If there is no place marker (%1, %2, etc.), a warning message is output and the result is undefined. Note that only placeholders between %1 and %99 are supported.

QString QString::arg ( const QString & a1, const QString & a2 ) const

This is an overloaded member function, provided for convenience.

This is the same as str.arg(a1).arg(a2), except that the strings are replaced in one pass. This can make a difference if a1 contains e.g. %1:

    QString str = "%1 %2";
    str.arg("%1f", "Hello");        // returns "%1f Hello"
    str.arg("%1f").arg("Hello");    // returns "Hellof"

QString QString::arg ( const QString & a1, const QString & a2, const QString & a3 ) const

This is an overloaded member function, provided for convenience.

This is the same as calling str.arg(a1).arg(a2).arg(a3), except that the strings are replaced in one pass.

QString QString::arg ( const QString & a1, const QString & a2, const QString & a3, const QString & a4 ) const

This is an overloaded member function, provided for convenience.

This is the same as calling str.arg(a1).arg(a2).arg(a3).arg(a4), except that the strings are replaced in one pass.

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

This is an overloaded member function, provided for convenience.

a is expressed in base base, which is 10 by default and must be between 2 and 36.

The fieldWidth value specifies the minimum amount of space that a is padded to and filled with the character fillChar. A positive value will produce a right-aligned number, whereas a negative value will produce a left-aligned number.

The '%' can be followed by an 'L', in which case the sequence is replaced with a localized representation of a. The conversion uses the default locale, set by QLocale::setDefaultLocale(). If no default locale was specified, the "C" locale is used. The 'L' flag is ignored if base is not 10.

    QString str;
    str = QString("Decimal 63 is %1 in hexadecimal")
            .arg(63, 0, 16);
    // str == "Decimal 63 is 3f in hexadecimal"

    QLocale::setDefaultLocale(QLocale::English, QLocale::UnitedStates);
    str = QString("%1 %L2 %L3")
            .arg(12345)
            .arg(12345)
            .arg(12345, 0, 16);
    // str == "12345 12,345 3039"

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

This is an overloaded member function, provided for convenience.

base is 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.

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

This is an overloaded member function, provided for convenience.

The fieldWidth value specifies the minimum amount of space that a is padded to and filled with the character fillChar. A positive value will produce a right-aligned number, whereas a negative value will produce a left-aligned number.

a is expressed in base 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::English, QLocale::UnitedStates);
    str = QString( "%1 %L2 %L3" )
            .arg( 12345 )
            .arg( 12345 )
            .arg( 12345, 0, 16 );
    // str == "12345 12,345 3039"

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

This is an overloaded member function, provided for convenience.

base is 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.

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

This is an overloaded member function, provided for convenience.

base is 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.

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

This is an overloaded member function, provided for convenience.

base is 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.

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

This is an overloaded member function, provided for convenience.

base is 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.

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

This is an overloaded member function, provided for convenience.

base is 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.

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

This is an overloaded member function, provided for convenience.

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

This is an overloaded member function, provided for convenience.

a is interpreted as a Latin-1 character.

QString QString::arg ( double a, int fieldWidth = 0, char fmt = 'g', int prec = -1, const QChar & fillChar = QLatin1Char( ' ' ) ) const

This is an overloaded member function, provided for convenience.

Argument a is formatted according to the fmt format specified, which is 'g' by default and can be any of the following:

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

With 'e', 'E', and 'f', prec is the number of digits after the decimal point. With 'g' and 'G', prec is the maximum number of significant digits (trailing zeroes are omitted).

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

The '%' can be followed by an 'L', in which case the sequence is replaced with a localized representation of a. The conversion uses the default locale, set by QLocale::setDefaultLocale(). If no default locale was specified, the "C" locale is used.

See also QLocale::toString().

const QChar QString::at ( int i ) const

Returns the character at index position i in the string.

i must be a valid index position in the string (i.e., 0 <= i < size()).

See also operator[]().

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

See also reserve() and squeeze().

void QString::chop ( int n )

Removes n characters from the end of the string.

If n is greater than size(), the result is an empty string.

Example:

    QString str("LOGOUT\r\n");
    str.chop(2);
    // str == "LOGOUT"

If you want to remove characters from the beginning of the string, use remove() instead.

See also truncate(), resize(), and remove().

void QString::clear ()

Clears the contents of the string and makes it empty.

See also resize() and isEmpty().

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

Lexically 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 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");   // x == 0
    int y = QString::compare("auto", "car");    // y < 0
    int z = QString::compare("car", "auto");    // z > 0

See also localeAwareCompare(), operator==(), operator<(), and operator>().

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

This is an overloaded member function, provided for convenience.

Same as compare(*this, other).

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. For convenience, the data is '\0'-terminated.

The pointer remains valid as long as the string isn't modified.

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

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 is an overloaded member function, provided for convenience.

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

bool QString::contains ( const QRegExp & rx ) const

This is an overloaded member function, provided for convenience.

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

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

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

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

See also contains() and indexOf().

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

This is an overloaded member function, provided for convenience.

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

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

This is an overloaded member function, provided for convenience.

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

This function counts overlapping matches, so in the example below, there are four instances of "ana" or "ama":

    QString str = "banana and panama";
    str.contains(QRegExp("a[nm]a"));    // returns 4

int QString::count () const

This is an overloaded member function, provided for convenience.

Same as size().

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. For convenience, the data is '\0'-terminated.

The pointer remains valid as long as the string isn't modified by other means.

Example:

    QString str = "Hello world";
    QChar *data = str.data();
    while (*data) {
        qDebug() << data->unicode();
        ++data;
    }

See also constData() and operator[]().

const QChar * QString::data () const

This is an overloaded member function, provided for convenience.

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 ( const QLatin1String & s, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const

This is an overloaded member function, provided for convenience.

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

This is an overloaded member function, provided for convenience.

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

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

Sets every character in the string to character ch. If size is different from -1 (the default), the string is resized to size beforehand.

Example:

    QString str = "Berlin";
    str.fill("z");
    // str == "zzzzzz"

    str.fill("A", 2);
    // str == "AA"

See also resize().

QString QString::fromAscii ( const char * str, int size = -1 )   [static]

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

If size is -1 (the default), it is taken to be qstrlen(str).

If a codec has been set using QTextCodec::setCodecForCStrings(), it is used to convert str to Unicode; otherwise this function does the same as fromLatin1().

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

QString QString::fromLatin1 ( const char * str, int size = -1 )   [static]

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

If size is -1 (the default), it is taken to be qstrlen(str).

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

QString QString::fromLocal8Bit ( const char * str, int size = -1 )   [static]

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

If size is -1 (the default), it is taken to be qstrlen(str).

QTextCodec::codecForLocale() is used to perform the conversion from Unicode.

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

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

Constructs a QString that uses the first size Unicode characters in the array unicode. The data in unicode is not copied. The caller must be able to guarantee that unicode will not be deleted or modified as long as the QString (or an unmodified copy of it) exists.

Any attempts to modify the QString or copies of it will cause it to create a deep copy of the data, ensuring that the raw data isn't modified.

Here's an example of how we can use a QRegExp on raw data in memory without requiring to copy the data into a QString:

    static const QChar unicode[] = {
        0x005A, 0x007F, 0x00A4, 0x0060, 0x1009, 0x0020,
        ...
        0x0020
    };
    int size = sizeof(unicode) / sizeof(QChar);

    QString str = QString::fromRawData(unicode, size);
    if (str.contains(QRegExp(pattern)))
    ...

Warning: A string created with fromRawData() is not '\0'-terminated, unless the raw data contains a '\0' character at position size. This means unicode() will not return a '\0'-terminated string (although utf16() does, at the cost of copying the raw data).

See also fromUtf16().

QString QString::fromStdString ( const std::string & str )   [static]

Returns a copy of str. str is converted to Unicode using fromAscii().

This constructor is only available if Qt is configured with STL compatibility enabled.

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

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

Returns a copy of str. str is assumed to be encoded in utf16 if the size of wchar_t is 2 bytes (e.g. on windows) and ucs4 if the size of wchar_t is 4 bytes (most Unix systems).

This constructor is only available if Qt is configured with STL compatibility enabled.

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

QString QString::fromUtf8 ( const char * str, int size = -1 )   [static]

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

If size is -1 (the default), it is taken to be qstrlen(str).

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

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

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

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

QString makes a deep copy of the Unicode data.

See also utf16() and setUtf16().

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

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

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

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

This is an overloaded member function, provided for convenience.

Returns the index position of the first occurrence of the character ch in the string, searching forward from index position from. Returns -1 if ch could not be found.

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

This is an overloaded member function, provided for convenience.

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

Example:

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

QString & QString::insert ( int i, const QString & str )

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

Example:

    QString str = "Meal";
    str.insert(1, QString("ontr"));
    // str == "Montreal"

If i is greater than size(), the array is first extended using resize().

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

QString & QString::insert ( int i, const QLatin1String & str )

This is an overloaded member function, provided for convenience.

Inserts the Latin-1 string str at index position i.

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

This is an overloaded member function, provided for convenience.

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

QString & QString::insert ( int i, QChar ch )

This is an overloaded member function, provided for convenience.

Inserts ch at index position i in the string.

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

See also isEmpty().

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

Returns the index position of the last occurrence of the string str in this string, searching backward from index position from. If from is -1 (the default), the search starts at the last character; if from is -2, at the next to last character and so on. Returns -1 if str is not found.

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

Example:

    QString x = "crazy azimuths";
    QString y = "az";
    x.lastIndexOf(y);           // returns 6
    x.lastIndexOf(y, 6);        // returns 6
    x.lastIndexOf(y, 5);        // returns 2
    x.lastIndexOf(y, 1);        // returns -1

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

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

This is an overloaded member function, provided for convenience.

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

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

This is an overloaded member function, provided for convenience.

Returns the index position of the last match of the regular expression rx in the string, searching backward from index position from. Returns -1 if rx didn't match anywhere.

Example:

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

QString QString::left ( int len ) const

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

The entire string is returned if len is greater than size() or less than zero.

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

See also right(), mid(), and startsWith().

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

Returns a string of size() width that contains this string padded by the fill character.

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

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 s = "apple";
    QString t = s.leftJustified(8, '.');        // t == "apple..."

See also rightJustified().

int QString::length () const

Same as size().

See also setLength().

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

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() and QTextCodec::locale().

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

This is an overloaded member function, provided for convenience.

Same as localeAwareCompare(*this, other).

QString QString::mid ( int i, int len = -1 ) const

Returns a string that contains the len characters of this string, starting at position i.

Returns an empty string if index i exceeds the length of the string. If there are less than len characters available in the string starting at position i, or if len is -1 (the default), the function returns all characters that are available from position i.

Example:

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

See also left() and right().

QString QString::normalized ( NormalizationForm form ) const

Returns the string in the given Unicode normalization form.

QString QString::normalized ( NormalizationForm form, QChar::UnicodeVersion version ) const

This is an overloaded member function, provided for convenience.

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

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

Returns a string equivalent of the number n to base base, which is 10 by default and must be between 2 and 36.

    long a = 63;
    QString str = QString::number(a, 16);             // str == "3f"
    QString str = QString::number(a, 16).upper();     // str == "3F"

See also setNum().

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

This is an overloaded member function, provided for convenience.

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

This is an overloaded member function, provided for convenience.

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

This is an overloaded member function, provided for convenience.

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

This is an overloaded member function, provided for convenience.

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

This is an overloaded member function, provided for convenience.

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

This is an overloaded member function, provided for convenience.

Argument n is formatted according to the format f, and the precision prec. The format f can be 'f', 'F', 'e', 'E', 'g' or 'G'. See arg() for an explanation of the formats.

Unlike QLocale::toString(), this function doesn't honor the user's locale settings.

See also setNum() and QLocale::toString().

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

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

Example:

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

See also append() and insert().

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

This is an overloaded member function, provided for convenience.

Prepends the Latin-1 string str to this string.

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

This is an overloaded member function, provided for convenience.

Prepends the byte array ba to this string. ba is converted to Unicode using fromAscii().

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 is an overloaded member function, provided for convenience.

Prepends the string str to this string. str is converted to Unicode using fromAscii().

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 ( QChar ch )

This is an overloaded member function, provided for convenience.

Prepends the character ch to this string.

void QString::push_back ( const QString & other )

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

void QString::push_back ( QChar ch )

This is an overloaded member function, provided for convenience.

Same as append(ch).

void QString::push_front ( const QString & other )

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

void QString::push_front ( QChar ch )

This is an overloaded member function, provided for convenience.

Same as prepend(ch).

QString & QString::remove ( int pos, int len )

Removes len characters from the string, starting at index position pos, and returns a reference to the string.

If pos is within the string, but pos + len is beyond the end of the string, the string is truncated at position pos.

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

See also insert() and replace().

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

This is an overloaded member function, provided for convenience.

Removes every occurrence of str in this string. 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).

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

This is an overloaded member function, provided for convenience.

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

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

Example:

    QString str = "Ali Baba";
    str.remove(QChar('a'), Qt::CaseInsensitive);
    // str == "li Bb"

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

QString & QString::remove ( const QRegExp & rx )

This is an overloaded member function, provided for convenience.

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

    QString str = "Telephone";
    str.remove(QRegExp("[aeiou]."));
    // str == "The"

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

QString & QString::replace ( int pos, int len, const QString & after )

Replaces len characters from index position pos with the string after, and returns a reference to this string.

Example:

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

See also insert() and remove().

QString & QString::replace ( int pos, int len, const QChar * unicode, int size )

This is an overloaded member function, provided for convenience.

Replaces len characters from index position pos with the first size characters of the QChar array unicode.

QString & QString::replace ( int pos, int len, QChar after )

This is an overloaded member function, provided for convenience.

Replaces len characters from index position pos with the character after.

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

This is an overloaded member function, provided for convenience.

Replaces every occurrence of the string before with the string after.

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

Example:

    QString str = "colour behaviour flavour neighbour";
    str.replace(QString("ou"), QString("o"));
    // str == "color behavior flavor neighbor"

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

This is an overloaded member function, provided for convenience.

Replaces every occurrence of the character ch in the string with after. Returns a reference to the string.

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

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

This is an overloaded member function, provided for convenience.

Replaces every occurrence of the character before with the character after. Returns a reference to the string.

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

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

This is an overloaded member function, provided for convenience.

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

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

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

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

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

void QString::reserve ( int size )

Attempts to allocate memory for at least size characters. If you know in advance how large the string will be, you can call this function, and if you resize the string often you are likely to get better performance. If size is an underestimate, the worst that will happen is that the QString will be a bit slower.

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 change the size of the string, call 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;
    int len = 0;
    result.reserve(maxSize);
    while (...) {
        result[len++] = getNextChar(); // fill part of the space
    }
    result.squeeze();

See also squeeze() and capacity().

void QString::resize ( int size )

Sets the size of the string to size characters.

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

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

Example:

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

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

If you want to append a certain number of identical characters to the string, use operator+=() as follows rather than resize():

    QString str = "Hello";
    str += QString(10, 'X');
    // str == "HelloXXXXXXXXXX"

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

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

See also truncate() and reserve().

QString QString::right ( int len ) const

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

The entire string is returned if len is greater than size() or less than zero.

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

See also left(), mid(), and endsWith().

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

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

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 = "apple";
    str = str.rightJustified(8, '.');
    // str == "...apple"

See also leftJustified().

QString QString::section ( QChar sep, int start, int end = -1, 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 csv = "forename,middlename,surname,phone";
    QString str = csv.section(',', 2, 2);   // str == "surname"

    QString path = "/usr/local/bin/myapp"; // First field is empty
    QString str = path.section('/', 3, 4);  // str == "bin/myapp"
    QString str = path.section('/', 3, 3, SectionSkipEmpty); // 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.

    QString csv = "forename,middlename,surname,phone";
    QString str = csv.section(',', -3, -2);  // str == "middlename,surname"

    QString path = "/usr/local/bin/myapp"; // First field is empty
    QString str = path.section('/', -1); // str == "myapp"

See also split().

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

This is an overloaded member function, provided for convenience.

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

See also split().

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

This is an overloaded member function, provided for convenience.

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

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

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

See also split() and simplified().

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

Sets the string to the printed value of n in base 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"

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

This is an overloaded member function, provided for convenience.

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

This is an overloaded member function, provided for convenience.

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

This is an overloaded member function, provided for convenience.

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

This is an overloaded member function, provided for convenience.

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

This is an overloaded member function, provided for convenience.

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

This is an overloaded member function, provided for convenience.

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

This is an overloaded member function, provided for convenience.

QString & QString::setNum ( double n, char f = 'g', int prec = 6 )

This is an overloaded member function, provided for convenience.

Sets the string to the printed value of n, formatted using format f with precision prec, and returns a reference to the string.

The format f can be 'f', 'F', 'e', 'E', 'g' or 'G'. See arg() for an explanation of the formats.

Unlike QLocale::toString(), this function doesn't honor the user's locale settings.

QString & QString::setNum ( float n, char f = 'g', int prec = 6 )

This is an overloaded member function, provided for convenience.

Sets the string to the printed value of n, formatted in format f with precision prec, and returns a reference to the string.

The format f can be 'f', 'F', 'e', 'E', 'g' or 'G'. See arg() for an explanation of the formats.

Unlike QLocale::toString(), this function doesn't honor the user's locale settings.

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

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

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

See also unicode() and setUtf16().

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

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

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

See also utf16() and setUnicode().

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

int QString::size () const

Returns the number of characters in this string.

The last character in the string is at position size() - 1. In addition, QString ensures that the character at position size() is always '\0', so that you can use the return value of data() and constData() as arguments to functions that expect '\0'-terminated strings.

Example:

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

See also isEmpty() and resize().

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

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

If cs is true, the string is only split only where characters are found that match sep exactly. If cs is false, the string is split, the string is split where characters are found that match sep case insensitively (e.g. "and" matches "AND").

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

Example:

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

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

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

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

This is an overloaded member function, provided for convenience.

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

This is an overloaded member function, provided for convenience.

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

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

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

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

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

Here's 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:

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

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

QString & QString::sprintf ( const char * cformat, ... )

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

The %lc escape sequence expects a unicode character of type ushort (as returned by QChar::unicode()). The %ls escape sequence expects a pointer to a zero-terminated array of unicode characters of type ushort (as returned by QString::utf16()).

The format string supports most of the conversion specifiers provided by printf() in the standard C++ library. It doesn't honor the length modifiers (e.g. h for short, ll for long long). If you need those, use the standard snprintf() function instead:

       char buf[BufSize];
       ::snprintf(buf, BufSize, "%lld", 123456789LL);
       QString str = QString::fromAscii(buf);

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

       QString result;
       QTextOStream(&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().

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 ( const QLatin1String & s, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const

This is an overloaded member function, provided for convenience.

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

This is an overloaded member function, provided for convenience.

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

QByteArray QString::toAscii () const

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

If a codec has been set using QTextCodec::setCodecForCStrings(), it is used to convert Unicode to 8-bit char; otherwise this function does the same as toLatin1().

See also fromAscii(), toLatin1(), toUtf8(), toLocal8Bit(), and QTextCodec.

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

Returns the string converted to a double value.

Returns 0.0 if the conversion fails.

If ok is not 0: if a conversion error occurs, *ok is set to false; otherwise *ok is set to true.

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

This function tries to interpret the string according to the current locale. The current locale is determined from the system at application startup and can be changed by calling QLocale::setDefault(). If the string cannot be interpreted according to the current locale, this function falls back on the "C" locale.

    bool ok;
    double d;

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

    QLocale::setDefault(QLocale::German);
    d = QString( "1234,56" ).toDouble(&ok); // ok == true, d == 1234.56
    d = QString( "1234.56" ).toDouble(&ok); // ok == true, d == 1234.56

Due to the ambiguity between the decimal point and thousands group separator in various locales, this function does not handle thousands group separators. If you need to convert such numbers, see QLocale::toDouble().

    bool ok;
    QLocale::setDefault(QLocale::C);
    double d = QString( "1,234,567.89" ).toDouble(&ok); // ok == false

Warning: If the string contains trailing whitespace this function will fail, and set *ok to false if ok is not 0. Leading whitespace is ignored.

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

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

Returns the string converted to a float value.

Returns 0.0 if the conversion fails.

If ok is not 0: if a conversion error occurs, *ok is set to false; otherwise *ok is set to true.

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

See also number(), toDouble(), and toInt().

int QString::toInt ( bool * ok = 0, 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 0: if a conversion error occurs, *ok is set to false; otherwise *ok is set to true.

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

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

See also number(), toUInt(), and toDouble().

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.

See also fromLatin1(), toAscii(), toUtf8(), toLocal8Bit(), and QTextCodec.

QByteArray QString::toLocal8Bit () const

Returns the local 8-bit representation of the string as a QByteArray. The returned byte array is undefined if the string contains characters not supported by the local 8-bit encoding.

QTextCodec::codecForLocale() is used to perform the conversion from Unicode.

See also fromLocal8Bit(), toAscii(), toLatin1(), toUtf8(), and QTextCodec.

long QString::toLong ( bool * ok = 0, 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 0: if a conversion error occurs, *ok is set to false; otherwise *ok is set to true.

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

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

See also number(), toULong(), and toInt().

qlonglong QString::toLongLong ( bool * ok = 0, 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 0: if a conversion error occurs, *ok is set to false; otherwise *ok is set to true.

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

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

See also number(), toULongLong(), and toInt().

QString QString::toLower () const

Returns a lowercase copy of the string.

    QString str = "TROlltECH";
    str = str.toLower();        // str == "trolltech"

See also toUpper().

short QString::toShort ( bool * ok = 0, 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 0: if a conversion error occurs, *ok is set to false; otherwise *ok is set to true.

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

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

See also number(), toUShort(), and toInt().

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

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

If the QString contains non-ASCII Unicode characters, using this operator can lead to loss of information. You can disable this operator by defining QT_NO_CAST_TO_ASCII when you compile your applications. You then need to call toAscii() (or toLatin1() or toUtf8() or toLocal8Bit()) explicitly if you want to convert the data to const char * and pass the return value on to the std::string constructor.

This operator is only available if Qt is configured with STL compatibility enabled.

See also toAscii(), toLatin1(), toUtf8(), and toLocal8Bit().

std::wstring QString::toStdWString () const

Returns a std::wstring object with the data contained in this QString. The std::wstring is encoded in utf16 on platforms where wchar_t is 2 bytes wide (e.g. windows) and in ucs4 on platforms where wchar_t is 4 bytes wide (most Unix systems).

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

This operator is only available if Qt is configured with STL compatibility enabled.

See also utf16(), toAscii(), toLatin1(), toUtf8(), and toLocal8Bit().

uint QString::toUInt ( bool * ok = 0, 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 0: if a conversion error occurs, *ok is set to false; otherwise *ok is set to true.

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

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

See also number() and toInt().

ulong QString::toULong ( bool * ok = 0, 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 0: if a conversion error occurs, *ok is set to false; otherwise *ok is set to true.

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

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

See also number().

qulonglong QString::toULongLong ( bool * ok = 0, 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 0: if a conversion error occurs, *ok is set to false; otherwise *ok is set to true.

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

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

See also number() and toLongLong().

ushort QString::toUShort ( bool * ok = 0, 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 0: if a conversion error occurs, *ok is set to false; otherwise *ok is set to true.

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

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

See also number() and toShort().

QString QString::toUpper () const

Returns an uppercase copy of the string.

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

See also toLower().

QByteArray QString::toUtf8 () const

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

See also fromUtf8(), toAscii(), toLatin1(), toLocal8Bit(), and QTextCodec.

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 ( int pos )

Truncates the string at index position pos.

If pos is beyond the end of the string, nothing happens.

Example:

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

See also chop(), resize(), and left().

const QChar * QString::unicode () const

Returns a '\0'-terminated Unicode representation of the string. The result remains valid until the string is modified.

See also setUnicode() and utf16().

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.

See also setUtf16() and unicode().

QString & QString::vsprintf ( const char * cformat, va_list ap )

Equivalent method to sprintf(), but takes a va_list ap instead a list of variable arguments. See the sprintf() 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 sprintf().

bool QString::operator!= ( const QString & other ) const

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

The comparison is based exclusively on the numeric Unicode values of the characters and is very fast, but is not what a human would expect. Consider sorting user-interface strings with localeAwareCompare().

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

This is an overloaded member function, provided for convenience.

bool QString::operator!= ( const QByteArray & other ) const

This is an overloaded member function, provided for convenience.

other is converted to a QString using fromAscii().

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.

bool QString::operator!= ( const char * other ) const

This is an overloaded member function, provided for convenience.

other is converted to a QString using fromAscii().

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 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+= ( const QLatin1String & str )

This is an overloaded member function, provided for convenience.

Appends the Latin-1 string str to this string.

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

This is an overloaded member function, provided for convenience.

Appends the byte array ba to this string. ba is converted to Unicode using fromAscii().

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 is an overloaded member function, provided for convenience.

Appends the string str to this string. str is converted to Unicode using fromAscii().

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+= ( char ch )

This is an overloaded member function, provided for convenience.

Appends the character ch to this string. The character is converted to Unicode using fromAscii().

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+= ( QChar ch )

This is an overloaded member function, provided for convenience.

Appends the character ch to the string.

bool QString::operator< ( const QString & other ) const

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

The comparison is based exclusively on the numeric Unicode values of the characters and is very fast, but is not what a human would expect. Consider sorting user-interface strings with localeAwareCompare().

bool QString::operator< ( const QLatin1String & other ) const

This is an overloaded member function, provided for convenience.

bool QString::operator< ( const QByteArray & other ) const

This is an overloaded member function, provided for convenience.

other is converted to a QString using fromAscii().

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.

bool QString::operator< ( const char * other ) const

This is an overloaded member function, provided for convenience.

other is converted to a QString using fromAscii().

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.

bool QString::operator<= ( const QString & other ) const

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

The comparison is based exclusively on the numeric Unicode values of the characters and is very fast, but is not what a human would expect. Consider sorting user-interface strings with localeAwareCompare().

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

This is an overloaded member function, provided for convenience.

bool QString::operator<= ( const QByteArray & other ) const

This is an overloaded member function, provided for convenience.

other is converted to a QString using fromAscii().

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.

bool QString::operator<= ( const char * other ) const

This is an overloaded member function, provided for convenience.

other is converted to a QString using fromAscii().

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 QString & other )

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

QString & QString::operator= ( const QLatin1String & str )

This is an overloaded member function, provided for convenience.

Assigns the Latin-1 string str to this string.

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

This is an overloaded member function, provided for convenience.

Assigns ba to this string. ba is converted to Unicode using fromAscii().

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

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

This is an overloaded member function, provided for convenience.

Assigns str to this string. str is converted to Unicode using fromAscii().

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= ( char ch )

This is an overloaded member function, provided for convenience.

Assigns character ch to this string. The character is converted to Unicode using fromAscii().

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= ( QChar ch )

This is an overloaded member function, provided for convenience.

Sets the string to contain the single character ch.

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

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

The comparison is based exclusively on the numeric Unicode values of the characters and is very fast, but is not what a human would expect. Consider sorting user-interface strings with localeAwareCompare().

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

This is an overloaded member function, provided for convenience.

bool QString::operator== ( const QByteArray & other ) const

This is an overloaded member function, provided for convenience.

other is converted to a QString using fromAscii().

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.

bool QString::operator== ( const char * other ) const

This is an overloaded member function, provided for convenience.

other is converted to a QString using fromAscii().

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.

bool QString::operator> ( const QString & other ) const

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

The comparison is based exclusively on the numeric Unicode values of the characters and is very fast, but is not what a human would expect. Consider sorting user-interface strings with localeAwareCompare().

bool QString::operator> ( const QLatin1String & other ) const

This is an overloaded member function, provided for convenience.

bool QString::operator> ( const QByteArray & other ) const

This is an overloaded member function, provided for convenience.

other is converted to a QString using fromAscii().

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.

bool QString::operator> ( const char * other ) const

This is an overloaded member function, provided for convenience.

other is converted to a QString using fromAscii().

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.

bool QString::operator>= ( const QString & other ) const

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

The comparison is based exclusively on the numeric Unicode values of the characters and is very fast, but is not what a human would expect. Consider sorting user-interface strings with localeAwareCompare().

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

This is an overloaded member function, provided for convenience.

bool QString::operator>= ( const QByteArray & other ) const

This is an overloaded member function, provided for convenience.

other is converted to a QString using fromAscii().

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.

bool QString::operator>= ( const char * other ) const

This is an overloaded member function, provided for convenience.

other is converted to a QString using fromAscii().

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.

QCharRef QString::operator[] ( int i )

Returns the character at index position i as a modifiable reference.

Example:

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

The return value is of type QCharRef, a helper class for QString. When you get an object of type QCharRef, you can use it as if it were a QChar &. If you assign to it, the assignment will apply to the character in the QString from which you got the reference.

See also at().

const QChar QString::operator[] ( int i ) const

This is an overloaded member function, provided for convenience.

Same as at(i).

QCharRef QString::operator[] ( uint i )

This is an overloaded member function, provided for convenience.

const QChar QString::operator[] ( uint i ) const

This is an overloaded member function, provided for convenience.


Related Non-Members

bool operator!= ( const char * s1, const QString & s2 )

This is an overloaded member function, provided for convenience.

Returns true if s1 is not equal to s2; otherwise returns false. Note that no string is equal to s1 being 0.

For s1 != 0, this is equivalent to compare(s1, s2) != 0.

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

This is an overloaded member function, provided for convenience.

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

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

This is an overloaded member function, provided for convenience.

Returns a string which is the result of concatenating the string s1 and the string s2. s2 is converted to Unicode using fromAscii().

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

This is an overloaded member function, provided for convenience.

Returns a string which is the result of concatenating the string s1 and string s2. s1 is converted to Unicode using fromAscii().

const QString operator+ ( const QString & s, char ch )

This is an overloaded member function, provided for convenience.

Returns a string which is the result of concatenating the string s and character ch.

const QString operator+ ( char ch, const QString & s )

This is an overloaded member function, provided for convenience.

Returns a string which is the result of concatenating the character ch and string s.

bool operator< ( const char * s1, const QString & s2 )

This is an overloaded member function, provided for convenience.

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

The comparison is based exclusively on the numeric Unicode values of the characters and is very fast, but is not what a human would expect. Consider sorting user-interface strings with QString::localeAwareCompare().

For s1 != 0, equivalent to compare(s1, s2) < 0.

QDataStream & operator<< ( QDataStream & out, const QString & str )

This is an overloaded member function, provided for convenience.

Writes the string str to the stream out.

See also Format of the QDataStream operators.

bool operator<= ( const char * s1, const QString & s2 )

This is an overloaded member function, provided for convenience.

Returns true if s1 is lexically less than or equal to s2; otherwise returns false.

The comparison is based exclusively on the numeric Unicode values of the characters and is very fast, but is not what a human would expect. Consider sorting user-interface strings with QString::localeAwareCompare().

For s1 != 0, this is equivalent to compare(s1, s2) <= 0.

bool operator== ( const char * s1, const QString & s2 )

This is an overloaded member function, provided for convenience.

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

Equivalent to s1 != 0 && compare(s1, s2) == 0.

bool operator> ( const char * s1, const QString & s2 )

This is an overloaded member function, provided for convenience.

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

The comparison is based exclusively on the numeric Unicode values of the characters and is very fast, but is not what a human would expect. Consider sorting user-interface strings with QString::localeAwareCompare().

Equivalent to compare(s1, s2) > 0.

bool operator>= ( const char * s1, const QString & s2 )

This is an overloaded member function, provided for convenience.

Returns true if s1 is lexically greater than or equal to s2; otherwise returns false.

The comparison is based exclusively on the numeric Unicode values of the characters and is very fast, but is not what a human would expect. Consider sorting user-interface strings with QString::localeAwareCompare().

For s1 != 0, this is equivalent to compare(s1, s2) >= 0.

QDataStream & operator>> ( QDataStream & in, QString & str )

This is an overloaded member function, provided for convenience.

Reads a string from the stream in into string str.

See also Format of the QDataStream operators.

Publicité

Best Of

Actualités les plus lues

Semaine
Mois
Année
  1. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 44
  2. Microsoft ouvre aux autres compilateurs C++ AMP, la spécification pour la conception d'applications parallèles C++ utilisant le GPU 22
  3. Les développeurs ignorent-ils trop les failles découvertes dans leur code ? Prenez-vous en compte les remarques des autres ? 17
  4. RIM : « 13 % des développeurs ont gagné plus de 100 000 $ sur l'AppWord », Qt et open-source au menu du BlackBerry DevCon Europe 0
  5. BlackBerry 10 : premières images du prochain OS de RIM qui devrait intégrer des widgets et des tuiles inspirées de Windows Phone 0
  6. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
  7. Adieu qmake, bienvenue qbs : Qt Building Suite, un outil déclaratif et extensible pour la compilation de projets Qt 17
Page suivante

Le blog Digia au hasard

Logo

Déploiement d'applications Qt Commercial sur les tablettes Windows 8

Le blog Digia est l'endroit privilégié pour la communication sur l'édition commerciale de Qt, où des réponses publiques sont apportées aux questions les plus posées au support. Lire l'article.

Communauté

Ressources

Liens utiles

Contact

  • Vous souhaitez rejoindre la rédaction ou proposer un tutoriel, une traduction, une question... ? Postez dans le forum Contribuez ou contactez-nous par MP ou par email (voir en bas de page).

Qt dans le magazine

Cette page est une traduction d'une page de la documentation de Qt, écrite par Nokia Corporation and/or its subsidiary(-ies). Les éventuels problèmes résultant d'une mauvaise traduction ne sont pas imputables à Nokia. Qt 4.1
Copyright © 2012 Developpez LLC. Tous droits réservés Developpez LLC. Aucune reproduction, même partielle, ne peut être faite de ce site et de l'ensemble de son contenu : textes, documents et images sans l'autorisation expresse de Developpez LLC. Sinon, vous encourez selon la loi jusqu'à 3 ans de prison et jusqu'à 300 000 E de dommages et intérêts. Cette page est déposée à la SACD.
Vous avez déniché une erreur ? Un bug ? Une redirection cassée ? Ou tout autre problème, quel qu'il soit ? Ou bien vous désirez participer à ce projet de traduction ? N'hésitez pas à nous contacter ou par MP !
 
 
 
 
Partenaires

Hébergement Web