Logo Search packages:      
Sourcecode: qt4-x11 version File versions  Download package

QString Class Reference

Inherited by QSettingsKey.

List of all members.


Detailed Description

The QString class provides a Unicode character string.

QString stores a string of 16-bit {QChar}s, 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 {QChar}s:

        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 lower case 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.

Definition at line 66 of file qstring.h.


Public Types

typedef const QCharconst_iterator
typedef const_iterator ConstIterator
typedef iterator Iterator
typedef QChariterator
enum  NormalizationForm { NormalizationForm_D, NormalizationForm_C, NormalizationForm_KD, NormalizationForm_KC }
enum  SectionFlag {
  SectionDefault = 0x00, SectionSkipEmpty = 0x01, SectionIncludeLeadingSep = 0x02, SectionIncludeTrailingSep = 0x04,
  SectionCaseInsensitiveSeps = 0x08
}
enum  SplitBehavior { KeepEmptyParts, SkipEmptyParts }

Public Member Functions

QStringappend (const QByteArray &s)
QStringappend (const char *s)
QStringappend (const QLatin1String &s)
QStringappend (const QString &s)
QStringappend (QChar c)
QString arg (const QString &a1, const QString &a2, const QString &a3, const QString &a4) const
QString arg (const QString &a1, const QString &a2, const QString &a3) const
QString arg (const QString &a1, const QString &a2) const
QString arg (const QString &a, int fieldWidth=0, 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
QString arg (ushort 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 (uint a, int fieldWidth=0, int base=10, const QChar &fillChar=QLatin1Char(' ')) const
QString arg (int 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 (long 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 (qlonglong a, int fieldwidth=0, int base=10, const QChar &fillChar=QLatin1Char(' ')) const
const QChar at (int i) const
const_iterator begin () const
iterator begin ()
int capacity () const
void chop (int n)
void clear ()
int compare (const QString &s) const
const_iterator constBegin () const
const QCharconstData () const
const_iterator constEnd () const
QBool contains (const QRegExp &rx) const
QBool contains (const QString &s, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
QBool contains (QChar c, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
int count (const QRegExp &) const
int count (const QString &s, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
int count (QChar c, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
int count () const
const QChardata () const
QChardata ()
void detach ()
const_iterator end () const
iterator end ()
bool endsWith (const QChar &c, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
bool endsWith (const QLatin1String &s, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
bool endsWith (const QString &s, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
QStringfill (QChar c, int size=-1)
int indexOf (const QRegExp &, int from=0) const
int indexOf (const QString &s, int from=0, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
int indexOf (QChar c, int from=0, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
QStringinsert (int i, const QLatin1String &s)
QStringinsert (int i, const QString &s)
QStringinsert (int i, const QChar *uc, int len)
QStringinsert (int i, QChar c)
bool isDetached () const
bool isEmpty () const
bool isNull () const
bool isRightToLeft () const
bool isSimpleText () const
int lastIndexOf (const QRegExp &, int from=-1) const
int lastIndexOf (const QString &s, int from=-1, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
int lastIndexOf (QChar c, int from=-1, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
QString left (int len) const
QString leftJustified (int width, QChar fill=QLatin1Char(' '), bool trunc=false) const
int length () const
int localeAwareCompare (const QString &s) const
QString mid (int i, int len=-1) const
QString normalized (NormalizationForm mode, QChar::UnicodeVersion version) const
QString normalized (NormalizationForm mode) const
bool operator!= (const QByteArray &s) const
bool operator!= (const char *s) const
bool operator!= (const QLatin1String &s) const
bool operator!= (const QString &s) const
QStringoperator+= (char c)
QStringoperator+= (const QByteArray &s)
QStringoperator+= (const char *s)
QStringoperator+= (const QLatin1String &s)
QStringoperator+= (const QString &s)
QStringoperator+= (QChar::SpecialCharacter c)
QStringoperator+= (QChar c)
bool operator< (const QByteArray &s) const
bool operator< (const char *s) const
bool operator< (const QLatin1String &s) const
bool operator< (const QString &s) const
bool operator<= (const QByteArray &s) const
bool operator<= (const char *s2) const
bool operator<= (const QLatin1String &s) const
bool operator<= (const QString &s) const
QStringoperator= (const Null &)
QStringoperator= (char c)
QStringoperator= (const QByteArray &a)
QStringoperator= (const char *ch)
QStringoperator= (const QLatin1String &)
QStringoperator= (const QString &)
QStringoperator= (QChar c)
bool operator== (const QByteArray &s) const
bool operator== (const char *s) const
bool operator== (const QLatin1String &s) const
bool operator== (const QString &s) const
bool operator> (const QByteArray &s) const
bool operator> (const char *s2) const
bool operator> (const QLatin1String &s) const
bool operator> (const QString &s) const
bool operator>= (const QByteArray &s) const
bool operator>= (const char *s2) const
bool operator>= (const QLatin1String &s) const
bool operator>= (const QString &s) const
QCharRef operator[] (uint i)
const QChar operator[] (uint i) const
QCharRef operator[] (int i)
const QChar operator[] (int i) const
QStringprepend (const QByteArray &s)
QStringprepend (const char *s)
QStringprepend (const QLatin1String &s)
QStringprepend (const QString &s)
QStringprepend (QChar c)
void push_back (const QString &s)
void push_back (QChar c)
void push_front (const QString &s)
void push_front (QChar c)
 QString (const Null &)
 QString (const QByteArray &a)
 QString (const char *ch)
 QString (const QString &)
 QString (const QLatin1String &latin1)
 QString (int size, QChar c)
 QString (QChar c)
 QString (const QChar *unicode, int size)
 QString ()
QStringremove (const QRegExp &rx)
QStringremove (const QString &s, Qt::CaseSensitivity cs=Qt::CaseSensitive)
QStringremove (QChar c, Qt::CaseSensitivity cs=Qt::CaseSensitive)
QStringremove (int i, int len)
QStringreplace (const QRegExp &rx, const QString &after)
QStringreplace (const QString &before, const QString &after, Qt::CaseSensitivity cs=Qt::CaseSensitive)
QStringreplace (QChar c, const QString &after, Qt::CaseSensitivity cs=Qt::CaseSensitive)
QStringreplace (QChar before, QChar after, Qt::CaseSensitivity cs=Qt::CaseSensitive)
QStringreplace (int i, int len, const QString &after)
QStringreplace (int i, int len, const QChar *s, int slen)
QStringreplace (int i, int len, QChar after)
void reserve (int size)
void resize (int size)
QString right (int len) const
QString rightJustified (int width, QChar fill=QLatin1Char(' '), bool trunc=false) const
QString section (const QRegExp &reg, int start, int end=-1, SectionFlags flags=SectionDefault) const
QString section (const QString &in_sep, int start, int end=-1, SectionFlags flags=SectionDefault) const
QString section (QChar sep, int start, int end=-1, SectionFlags flags=SectionDefault) const
QStringsetNum (double, char f='g', int prec=6)
QStringsetNum (float, char f='g', int prec=6)
QStringsetNum (qulonglong, int base=10)
QStringsetNum (qlonglong, int base=10)
QStringsetNum (ulong, int base=10)
QStringsetNum (long, int base=10)
QStringsetNum (uint, int base=10)
QStringsetNum (int, int base=10)
QStringsetNum (ushort, int base=10)
QStringsetNum (short, int base=10)
QStringsetUnicode (const QChar *unicode, int size)
QStringsetUtf16 (const ushort *utf16, int size)
QString simplified () const
int size () const
QStringList split (const QRegExp &sep, SplitBehavior behavior=KeepEmptyParts) const
QStringList split (const QChar &sep, SplitBehavior behavior=KeepEmptyParts, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
QStringList split (const QString &sep, SplitBehavior behavior=KeepEmptyParts, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
QStringsprintf (const char *format,...)
void squeeze ()
bool startsWith (const QChar &c, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
bool startsWith (const QLatin1String &s, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
bool startsWith (const QString &s, 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
QStdWString 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
QString toUpper () const
ushort toUShort (bool *ok=0, int base=10) const
QByteArray toUtf8 () const
QString trimmed () const
void truncate (int pos)
const QCharunicode () const
const ushort * utf16 () const
QStringvsprintf (const char *format, va_list ap)
 ~QString ()

Static Public Member Functions

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

Static Public Attributes

static const Null null = QString::Null()

Private Member Functions

void expand (int i)
QString multiArg (int numArgs, const QString **args) const
 QString (Data *dd, int)
void realloc (int alloc)
void realloc ()
int toWCharArray (wchar_t *array) const
void updateProperties () const

Static Private Member Functions

static void free (Data *)
static Data * fromLatin1_helper (const char *str, int size=-1)
static QString fromWCharArray (const wchar_t *, int)
static int grow (int)

Private Attributes

Data * d

Static Private Attributes

static QTextCodeccodecForCStrings
static Data shared_empty = { Q_ATOMIC_INIT(1), 0, 0, shared_empty.array, 0, 0, 0, 0, 0, {0} }
static Data shared_null = { Q_ATOMIC_INIT(1), 0, 0, shared_null.array, 0, 0, 0, 0, 0, {0} }

Friends

class QCharRef
class QTextCodec

Related Functions

(Note that these are not member functions.)

bool operator!= (const char *s1, const QString &s2)
const QString operator+ (char ch, const QString &s)
const QString operator+ (const QString &s, char ch)
const QString operator+ (const char *s1, const QString &s2)
const QString operator+ (const QString &s1, const char *s2)
const QString operator+ (const QString &s1, const QString &s2)
bool operator< (const char *s1, const QString &s2)
QDataStreamoperator<< (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)
QDataStreamoperator>> (QDataStream &in, QString &str)

Classes

struct  Data
struct  Null

The documentation for this class was generated from the following files:

Generated by  Doxygen 1.6.0   Back to index