QString 类

The QString 类提供 Unicode 字符串。 更多...

头: #include <QString>
继承者: QConstString , QDBusObjectPath ,和 QDBusSignature

注意: 此类的所有函数 可重入 , except for ascii (), latin1 (), utf8 (),和 local8Bit (), which are nonreentrant.

公共类型

class Null
typedef ConstIterator
typedef Iterator
enum NormalizationForm { NormalizationForm_D, NormalizationForm_C, NormalizationForm_KD, NormalizationForm_KC }
enum SectionFlag { SectionDefault, SectionSkipEmpty, SectionIncludeLeadingSep, SectionIncludeTrailingSep, SectionCaseInsensitiveSeps }
flags SectionFlags
enum SplitBehavior { KeepEmptyParts, SkipEmptyParts }
typedef const_iterator
typedef const_reference
typedef iterator
typedef reference
typedef value_type

公共函数

QString ()
QString (const QChar * unicode , int size )
QString (const QChar * unicode )
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 ()
QString & append (const QString & str )
QString & append (const QStringRef & reference )
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 (const QString & a1 , const QString & a2 , const QString & a3 , const QString & a4 , const QString & a5 ) const
QString arg (const QString & a1 , const QString & a2 , const QString & a3 , const QString & a4 , const QString & a5 , const QString & a6 ) const
QString arg (const QString & a1 , const QString & a2 , const QString & a3 , const QString & a4 , const QString & a5 , const QString & a6 , const QString & a7 ) const
QString arg (const QString & a1 , const QString & a2 , const QString & a3 , const QString & a4 , const QString & a5 , const QString & a6 , const QString & a7 , const QString & a8 ) const
QString arg (const QString & a1 , const QString & a2 , const QString & a3 , const QString & a4 , const QString & a5 , const QString & a6 , const QString & a7 , const QString & a8 , const QString & a9 ) 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 format = 'g', int precision = -1, const QChar & fillChar = QLatin1Char( ' ' )) const
const QChar at (int position ) const
iterator begin ()
const_iterator begin () const
int capacity () const
void chop (int n )
void clear ()
int compare (const QString & other ) const
int compare (const QString & other , Qt::CaseSensitivity cs ) const
int compare (const QLatin1String & other , Qt::CaseSensitivity cs = Qt::CaseSensitive) const
int compare (const QStringRef & ref , Qt::CaseSensitivity cs = Qt::CaseSensitive) const
const_iterator constBegin () const
const QChar * constData () const
const_iterator constEnd () const
bool contains (const QString & str , Qt::CaseSensitivity cs = Qt::CaseSensitive) const
bool contains (const QStringRef & str , Qt::CaseSensitivity cs = Qt::CaseSensitive) const
bool contains (QChar ch , Qt::CaseSensitivity cs = Qt::CaseSensitive) const
bool contains (const QRegExp & rx ) const
bool contains (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 QStringRef & str , Qt::CaseSensitivity cs = Qt::CaseSensitive) const
int count (const QRegExp & rx ) const
int count () const
QChar * data ()
const QChar * data () const
iterator end ()
const_iterator end () const
bool endsWith (const QString & s , Qt::CaseSensitivity cs = Qt::CaseSensitive) const
bool endsWith (const QStringRef & s , Qt::CaseSensitivity cs = Qt::CaseSensitive) const
bool endsWith (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 (const QLatin1String & 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 QStringRef & str , int from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
int indexOf (const QRegExp & rx , int from = 0) const
int indexOf (QRegExp & rx , int from = 0) const
QString & insert (int position , const QString & str )
QString & insert (int position , const QLatin1String & str )
QString & insert (int position , const QChar * unicode , int size )
QString & insert (int position , QChar ch )
bool isEmpty () const
bool isNull () const
bool isRightToLeft () const
int lastIndexOf (const QString & str , int from = -1, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
int lastIndexOf (const QLatin1String & 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 QStringRef & str , int from = -1, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
int lastIndexOf (const QRegExp & rx , int from = -1) const
int lastIndexOf (QRegExp & rx , int from = -1) const
QString left (int n ) const
QString leftJustified (int width , QChar fill = QLatin1Char( ' ' ), bool truncate = false) const
QStringRef leftRef (int n ) const
int length () const
int localeAwareCompare (const QStringRef & other ) const
int localeAwareCompare (const QString & other ) const
QString mid (int position , int n = -1) const
QStringRef midRef (int position , int n = -1) const
QString normalized (NormalizationForm mode ) const
QString normalized (NormalizationForm mode , 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 position , int n )
QString & remove (QChar ch , Qt::CaseSensitivity cs = Qt::CaseSensitive)
QString & remove (const QString & str , Qt::CaseSensitivity cs = Qt::CaseSensitive)
QString & remove (const QRegExp & rx )
QString repeated (int times ) const
QString & replace (int position , int n , const QString & after )
QString & replace (int position , int n , const QChar * unicode , int size )
QString & replace (int position , int n , QChar after )
QString & replace (const QString & before , const QString & after , Qt::CaseSensitivity cs = Qt::CaseSensitive)
QString & replace (const QChar * before , int blen , const QChar * after , int alen , Qt::CaseSensitivity cs = Qt::CaseSensitive)
QString & replace (QChar ch , const QString & after , Qt::CaseSensitivity cs = Qt::CaseSensitive)
QString & replace (QChar before , QChar after , Qt::CaseSensitivity cs = Qt::CaseSensitive)
QString & replace (const QLatin1String & before , const QLatin1String & after , Qt::CaseSensitivity cs = Qt::CaseSensitive)
QString & replace (const QLatin1String & before , const QString & after , Qt::CaseSensitivity cs = Qt::CaseSensitive)
QString & replace (const QString & before , const QLatin1String & after , Qt::CaseSensitivity cs = Qt::CaseSensitive)
QString & replace (QChar c , const QLatin1String & 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 n ) const
QString rightJustified (int width , QChar fill = QLatin1Char( ' ' ), bool truncate = false) const
QStringRef rightRef (int n ) 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 format = 'g', int precision = 6)
QString & setNum (float n , char format = 'g', int precision = 6)
QString & setRawData (const QChar * unicode , int size )
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
bool startsWith (const QStringRef & s , Qt::CaseSensitivity cs = Qt::CaseSensitive) const
void swap (QString & other )
QByteArray toAscii () const
QString toCaseFolded () 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
QVector<uint> toUcs4 () const
QString toUpper () const
QByteArray toUtf8 () const
int toWCharArray (wchar_t * array ) const
QString trimmed () const
void truncate (int position )
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+= (const QStringRef & 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= (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 position )
const QChar operator[] (int position ) const
QCharRef operator[] (uint position )
const QChar operator[] (uint position ) const

静态公共成员

int compare (const QString & s1 , const QString & s2 , Qt::CaseSensitivity cs )
int compare (const QString & s1 , const QString & s2 )
int compare (const QString & s1 , const QLatin1String & s2 , Qt::CaseSensitivity cs = Qt::CaseSensitive)
int compare (const QLatin1String & s1 , const QString & s2 , Qt::CaseSensitivity cs = Qt::CaseSensitive)
int compare (const QString & s1 , const QStringRef & s2 , Qt::CaseSensitivity cs = Qt::CaseSensitive)
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 fromUcs4 (const uint * unicode , int size = -1)
QString fromUtf8 (const char * str , int size = -1)
QString fromUtf16 (const ushort * unicode , int size = -1)
QString fromWCharArray (const wchar_t * string , int size = -1)
int localeAwareCompare (const QString & s1 , const QString & s2 )
int localeAwareCompare (const QString & s1 , const QStringRef & s2 )
QString number (long n , int base = 10)
QString number (double n , char format = 'g', int precision = 6)
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)
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+ (char ch , const QString & s )
const QString operator+ (const QString & s , char ch )
bool operator< (const char * s1 , const QString & s2 )
QDataStream & operator<< (QDataStream & stream , const QString & string )
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 & stream , QString & string )

QT_NO_CAST_FROM_ASCII
QT_NO_CAST_TO_ASCII

详细描述

The QString 类提供 Unicode 字符串。

QString stores a string of 16-bit QChar ,其中各 QChar corresponds one Unicode 4.0 character. (Unicode characters with code values above 65535 are stored using surrogate pairs, i.e., two consecutive QChar )。

Unicode 是支持当今使用的大多数书写系统的国际标准。它是 US-ASCII (ANSI X3.4-1986) 和 Latin-1 (ISO 8859-1) 的超集,且所有 US-ASCII/Latin-1 字符可用于相同代码位置。

Behind the scenes, QString 使用 隐式共享 (写时拷贝) 以缩减内存用量并避免不必要的数据拷贝。这还有助于缩减存储 16 位字符而不是 8 位字符的固有开销。

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

初始化字符串

一种方式初始化 QString 是只需传递 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 * 数据成 Unicode 使用 fromAscii () function. By default, fromAscii () treats character above 128 as Latin-1 characters, but this can be changed by calling QTextCodec::setCodecForCStrings ().

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

还可以将字符串数据提供成数组化的 QChar

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

另一种方式是设置字符串大小使用 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[] () 返回可以用于赋值左侧的字符引用。例如:

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

对于只读访问,替代句法是使用 at () 函数:

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

The at () 函数可以更快相比 operator[] (), because it never causes a 深拷贝 的出现。另外,使用 left (), right (),或 mid () 函数能一次提取几个字符。

A QString can embed '\0' characters ( QChar::Null )。 size () 函数始终返回整个字符串的大小,包括嵌入 \0 字符。

后于调用 resize () 函数,新近分配字符拥有未定义值。要把字符串中的所有字符设为特定值,使用 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:

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

You can also pass string literals to functions that take QStrings as arguments, invoking the QString (const char *) constructor. Similarly, you can pass a QString to a function that takes a const char * 自变量使用 qPrintable () macro which returns the given QString 作为 const char * . This is equivalent to calling < QString >. toLocal8Bit (). constData ().

操纵字符串数据

QString provides the following basic functions for modifying the character data: append (), prepend (), insert (), replace (),和 remove ()。例如:

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

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

The replace () 和 remove () functions' first two arguments are the position from which to start erasing and the number of characters that should be erased. If you want to replace all occurrences of a particular substring with another, use one of the two-parameter replace () overloads.

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

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

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

QString provides many functions for converting numbers into strings and strings into numbers. See the arg () 函数, setNum () 函数, number () 静态函数,和 toInt (), toDouble (),及类似函数。

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

字符串列表的处理是通过 QStringList 类。可以把字符串分割成字符串列表使用 split () 函数,和把字符串列表联接成单字符串采用可选分隔符使用 QStringList::join (). You can obtain a list of strings from a string list that contain a particular substring or that match a particular QRegExp 使用 QStringList::filter () 函数。

查询字符串数据

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

可以比较 QString 使用重载运算符譬如 operator< (), operator<= (), operator== (), operator>= (), and so on. Note that the comparison is based exclusively on the numeric Unicode values of the characters. It is very fast, but is not what a human would expect; the QString::localeAwareCompare () function is a better choice for sorting user-interface strings.

要获得实际字符数据指针,调用 data () 或 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 .

在 8 位字符串和 Unicode 字符串之间转换

QString provides the following four functions that return a const char * 版本的字符串如 QByteArray : toAscii (), toLatin1 (), toUtf8 (),和 toLocal8Bit ().

  • toAscii () returns an 8-bit string encoded using the codec specified by QTextCodec::codecForCStrings (by default, that is Latin 1).
  • toLatin1 () 返回 Latin-1 (ISO 8859-1) 编码 8 位字符串。
  • toUtf8 () 返回 UTF-8 编码 8 位字符串。UTF-8 是 US-ASCII (ANSI X3.4-1986) 超集,支持透过多字节序列的整个 Unicode 字符集。
  • toLocal8Bit () returns an 8-bit string using the system's local encoding.

To convert from one of these encodings, QString 提供 fromAscii (), fromLatin1 (), fromUtf8 (),和 fromLocal8Bit ()。其它编码的支持是透过 QTextCodec 类。

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

  • QT_NO_CAST_FROM_ASCII disables automatic conversions from C string literals and pointers to Unicode.
  • QT_NO_CAST_TO_ASCII disables automatic conversion from QString to C strings.

One way to define these preprocessor symbols globally for your application is to add the following entry to your qmake 工程文件 :

DEFINES += QT_NO_CAST_FROM_ASCII \
           QT_NO_CAST_TO_ASCII
					

You then need to explicitly call fromAscii (), fromLatin1 (), fromUtf8 (),或 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/");
					

同样,必须调用 toAscii (), toLatin1 (), toUtf8 (),或 toLocal8Bit () explicitly to convert the QString to an 8-bit string. (Other encodings are supported through the QTextCodec class.)

C 程序员注意事项
Due to C++'s type system and the fact that QString is 隐式共享 ,可以视 QString 像 int 或其它基本类型。例如:
QString Widget::boolToString(bool b)
{


QString


 result;

if

 (b)
result

=


"True"

;

else

result

=


"False"

;

return

 result;
}
								

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

null 和空字符串之间的区别

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
						

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

自变量格式

成员函数中的自变量 format 可以指定 (如: arg (), number ()),自变量 format can be one of the following:

格式 含义
e format as [-]9.9e[+|-]999
E format as [-]9.9E[+|-]999
f format as [-]9.9
g 使用 e or f format, whichever is the most concise
G 使用 E or f format, whichever is the most concise

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

更高效的字符串构造

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

    QString foo;
    QString type = "long";
    foo->setText(QLatin1String("vector<") + type + QLatin1String(">::iterator"));
    if (foo.startsWith("(" + type + ") 0x"))
        ...
						

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

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

Second, QLatin1String does not store its length internally but calls qstrlen () when it needs to know its length.

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

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

QLatin1Literal is a second internal class that can replace QLatin1String , which can't be changed for compatibility reasons. QLatin1Literal stores its length, thereby saving time when QStringBuilder computes the amount of memory required for the final string.

Additional efficiency is gained by inlining and reduced reference counting (the QString created from a QStringBuilder typically has a ref count of 1, whereas QString::append () 需要额外测试)。

There are three ways you can access this improved method of string construction. The straightforward way is to include QStringBuilder wherever you want to use it, and use the '%' 运算符而不是 '+' 当串联字符串时:

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

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

    DEFINES *= QT_USE_QSTRINGBUILDER
						

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

另请参阅 fromRawData (), QChar , QLatin1String , QByteArray ,和 QStringRef .

成员类型文档编制

typedef QString:: ConstIterator

Qt 样式同义词 QString::const_iterator .

typedef QString:: Iterator

Qt 样式同义词 QString::iterator .

enum QString:: NormalizationForm

此枚举描述 Unicode 文本的各种规范化形式。

常量 描述
QString::NormalizationForm_D 0 典型分解
QString::NormalizationForm_C 1 典型分解,紧接着是典型合成
QString::NormalizationForm_KD 2 兼容性分解
QString::NormalizationForm_KC 3 兼容性分解,紧接着是典型合成

另请参阅 normalized () 和 Unicode 标准附录 #15 .

enum QString:: SectionFlag
flags QString:: SectionFlags

This enum specifies flags that can be used to affect various aspects of the section () function's behavior with respect to separators and empty fields.

常量 描述
QString::SectionDefault 0x00 Empty fields are counted, leading and trailing separators are not included, and the separator is compared case sensitively.
QString::SectionSkipEmpty 0x01 Treat empty fields as if they don't exist, i.e. they are not considered as far as start and end are concerned.
QString::SectionIncludeLeadingSep 0x02 Include the leading separator (if any) in the result string.
QString::SectionIncludeTrailingSep 0x04 Include the trailing separator (if any) in the result string.
QString::SectionCaseInsensitiveSeps 0x08 比较分隔符不区分大小写。

SectionFlags 类型是 typedef 对于 QFlags <SectionFlag>. It stores an OR combination of SectionFlag values.

另请参阅 section ().

enum QString:: SplitBehavior

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

常量 描述
QString::KeepEmptyParts 0 若字段为空,将它保持在结果中。
QString::SkipEmptyParts 1 若字段为空,不将它包括在结果中。

另请参阅 split ().

typedef QString:: const_iterator

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

另请参阅 QString::iterator .

typedef QString:: const_reference

The QString::const_reference typedef provides an STL-style const reference for QString .

This typedef was introduced in Qt 4.8.

typedef QString:: iterator

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

另请参阅 QString::const_iterator .

typedef QString:: reference

The QString::const_reference typedef provides an STL-style reference for QString .

This typedef was introduced in Qt 4.8.

typedef QString:: value_type

The QString::const_reference typedef provides an STL-style value type for QString .

This typedef was introduced in Qt 4.8.

成员函数文档编制

QString:: QString ()

Constructs a null string. Null strings are also empty.

另请参阅 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. The unicode data is copied as is and the Byte Order Mark is preserved if present.

QString:: QString (const QChar * unicode )

Constructs a string initialized with the characters of the QChar array unicode , which must be terminated with a 0.

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

该函数在 Qt 4.7 引入。

QString:: QString ( QChar ch )

Constructs a string of size 1 containing the character ch .

QString:: QString ( int size , QChar ch )

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

另请参阅 fill ().

QString:: QString (const QLatin1String & str )

Constructs a copy of the Latin-1 string str .

另请参阅 fromLatin1 ().

QString:: QString (const QString & other )

构造副本为 other .

此操作花费 常量时间 ,因为 QString is 隐式共享 . 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 线性时间 .

另请参阅 operator= ().

QString:: QString (const char * str )

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

另请参阅 fromAscii (), fromLatin1 (), fromLocal8Bit (),和 fromUtf8 ().

QString:: QString (const QByteArray & ba )

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

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

另请参阅 fromAscii (), fromLatin1 (), fromLocal8Bit (),和 fromUtf8 ().

QString:: ~QString ()

销毁字符串。

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

追加字符串 str 到此字符串末尾。

范例:

QString x = "free";
QString y = "dom";
x.append(y);
// x == "freedom"
						

这如同使用 insert () 函数:

x.insert(x.size(), y);
						

append() 函数通常非常快 ( 常量时间 ),因为 QString preallocates extra space at the end of the string data so it can grow without reallocating the entire string each time.

另请参阅 operator+= (), prepend (),和 insert ().

QString & QString:: append (const QStringRef & reference )

追加给定字符串 reference to this string and returns the result.

该函数在 Qt 4.4 引入。

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

此函数重载 append ().

追加 Latin-1 字符串 str 到此字符串。

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

此函数重载 append ().

追加字节数组 ba to this string. The given byte array is converted to Unicode using the fromAscii () 函数。

可以禁用此函数通过定义 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 )

此函数重载 append ().

追加字符串 str to this string. The given const char pointer is converted to Unicode using the fromAscii () 函数。

可以禁用此函数通过定义 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 )

此函数重载 append ().

追加字符 ch 到此字符串。

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

返回字符串副本,替换最小编号位置标记为字符串 a ,即: %1 , %2 , ..., %99 .

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

此范例展示如何创建 status 字符串为处理文件列表时报告进度:

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

首先, arg(i) 替换 %1 。然后 arg(total) 替换 %2 。最后, arg(fileName) 替换 %3 .

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

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

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

此函数重载 arg ().

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

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

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

此函数重载 arg ().

这如同调用 str.arg(a1).arg(a2).arg(a3) , except that the strings a1 , a2 and a3 are replaced in one pass.

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

此函数重载 arg ().

这如同调用 str.arg(a1).arg(a2).arg(a3).arg(a4) , except that the strings a1 , a2 , a3 and a4 are replaced in one pass.

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

此函数重载 arg ().

这如同调用 str.arg(a1).arg(a2).arg(a3).arg(a4).arg(a5) , except that the strings a1 , a2 , a3 , a4 ,和 a5 are replaced in one pass.

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

此函数重载 arg ().

这如同调用 str.arg(a1).arg(a2).arg(a3).arg(a4).arg(a5).arg(a6)) , except that the strings a1 , a2 , a3 , a4 , a5 ,和 a6 are replaced in one pass.

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

此函数重载 arg ().

这如同调用 str.arg(a1).arg(a2).arg(a3).arg(a4).arg(a5).arg(a6).arg(a7) , except that the strings a1 , a2 , a3 , a4 , a5 , a6 ,和 a7 are replaced in one pass.

QString QString:: arg (const QString & a1 , const QString & a2 , const QString & a3 , const QString & a4 , const QString & a5 , const QString & a6 , const QString & a7 , const QString & a8 ) const

此函数重载 arg ().

这如同调用 str.arg(a1).arg(a2).arg(a3).arg(a4).arg(a5).arg(a6).arg(a7).arg(a8) , except that the strings a1 , a2 , a3 , a4 , a5 , a6 , a7 ,和 a8 are replaced in one pass.

QString QString:: arg (const QString & a1 , const QString & a2 , const QString & a3 , const QString & a4 , const QString & a5 , const QString & a6 , const QString & a7 , const QString & a8 , const QString & a9 ) const

此函数重载 arg ().

这如同调用 str.arg(a1).arg(a2).arg(a3).arg(a4).arg(a5).arg(a6).arg(a7).arg(a8).arg(a9) , except that the strings a1 , a2 , a3 , a4 , a5 , a6 , a7 , a8 ,和 a9 are replaced in one pass.

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

此函数重载 arg ().

The a argument is expressed in base base , which is 10 by default and must be between 2 and 36. For bases other than 10, a is treated as an unsigned integer.

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

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

QString str;
str = QString("Decimal 63 is %1 in hexadecimal")
        .arg(63, 0, 16);
// str == "Decimal 63 is 3f in hexadecimal"
QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedStates));
str = QString("%1 %L2 %L3")
        .arg(12345)
        .arg(12345)
        .arg(12345, 0, 16);
// str == "12345 12,345 3039"
						

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

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

此函数重载 arg ().

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

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

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

此函数重载 arg ().

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

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

The '%' can be followed by an 'L', in which case the sequence is replaced with a localized representation of a . The conversion uses the default locale. The default locale is determined from the system's locale settings at application startup. It can be changed using QLocale::setDefault (). The 'L' flag is ignored if base is not 10.

QString str;
str = QString("Decimal 63 is %1 in hexadecimal")
        .arg(63, 0, 16);
// str == "Decimal 63 is 3f in hexadecimal"
QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedStates));
str = QString("%1 %L2 %L3")
        .arg(12345)
        .arg(12345)
        .arg(12345, 0, 16);
// str == "12345 12,345 3039"
						

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

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

此函数重载 arg ().

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

The base argument specifies the base to use when converting the integer a to a string. The base must be between 2 and 36, with 8 giving octal, 10 decimal, and 16 hexadecimal numbers.

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

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

此函数重载 arg ().

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

The base argument specifies the base to use when converting the integer a into a string. The base must be between 2 and 36, with 8 giving octal, 10 decimal, and 16 hexadecimal numbers.

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

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

此函数重载 arg ().

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

The base argument specifies the base to use when converting the integer a into a string. base must be between 2 and 36, with 8 giving octal, 10 decimal, and 16 hexadecimal numbers.

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

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

此函数重载 arg ().

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

The base argument specifies the base to use when converting the integer a into a string. The base must be between 2 and 36, with 8 giving octal, 10 decimal, and 16 hexadecimal numbers.

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

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

此函数重载 arg ().

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

The base argument specifies the base to use when converting the integer a into a string. The base must be between 2 and 36, with 8 giving octal, 10 decimal, and 16 hexadecimal numbers.

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

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

此函数重载 arg ().

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

此函数重载 arg ().

The a 自变量被解释成 Latin-1 字符。

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

此函数重载 arg ().

自变量 a is formatted according to the specified format and precision 。见 自变量格式 了解细节。

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

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

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.

fillChar is '0' (the number 0, ASCII 48), this function will use the locale's zero to pad. For negative numbers, the zero padding will probably appear before the minus sign.

另请参阅 QLocale::toString ().

const QChar QString:: at ( int position ) const

返回字符按给定索引 position 在字符串中。

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

另请参阅 operator[] ().

iterator QString:: begin ()

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

另请参阅 constBegin () 和 end ().

const_iterator QString:: begin () const

此函数重载 begin ().

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

另请参阅 reserve () 和 squeeze ().

void QString:: chop ( int n )

移除 n 个字符从字符串末尾起。

n 大于 size (), the result is an empty string.

范例:

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

若想要移除字符从 beginning 对于字符串,使用 remove () 代替。

另请参阅 truncate (), resize (),和 remove ().

void QString:: clear ()

Clears the contents of the string and makes it empty.

另请参阅 resize () 和 isEmpty ().

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

比较 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 .

cs is Qt::CaseSensitive , the comparison is case sensitive; otherwise the comparison is case insensitive.

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

int x = QString::compare("aUtO", "AuTo", Qt::CaseInsensitive);  // x == 0
int y = QString::compare("auto", "Car", Qt::CaseSensitive);     // y > 0
int z = QString::compare("auto", "Car", Qt::CaseInsensitive);   // z < 0
						

该函数在 Qt 4.2 引入。

另请参阅 operator== (), operator< (),和 operator> ().

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

此函数重载 compare ().

Performs a case sensitive compare of s1 and s2 .

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

此函数重载 compare ().

履行比较为 s1 and s2 ,使用区分大小写设置 cs .

该函数在 Qt 4.2 引入。

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

此函数重载 compare ().

履行比较为 s1 and s2 ,使用区分大小写设置 cs .

该函数在 Qt 4.2 引入。

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

此函数重载 compare ().

Lexically compares this string with the other string and returns an integer less than, equal to, or greater than zero if this string is less than, equal to, or greater than the other string.

相当于 compare(*this, other) .

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

此函数重载 compare ().

如同 compare(*this, other , cs ).

该函数在 Qt 4.2 引入。

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

此函数重载 compare ().

如同 compare(*this, other , cs ).

该函数在 Qt 4.2 引入。

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

此函数重载 compare ().

Compares the string reference, ref , with the string and returns an integer less than, equal to, or greater than zero if the string is less than, equal to, or greater than ref .

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

此函数重载 compare ().

const_iterator QString:: constBegin () const

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

另请参阅 begin () 和 constEnd ().

const QChar * QString:: constData () const

返回指针指向的数据存储在 QString . The pointer can be used to access the characters that compose the string. For convenience, the data is '\0'-terminated.

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

另请参阅 data () 和 operator[] ().

const_iterator QString:: constEnd () const

Returns a const STL-style iterator pointing to the imaginary item after the last item in the list.

另请参阅 constBegin () 和 end ().

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

Returns true if this string contains an occurrence of the string str ;否则返回 false。

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

范例:

QString str = "Peter Pan";
str.contains("peter", Qt::CaseInsensitive);    // returns true
						

另请参阅 indexOf () 和 count ().

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

Returns true if this string contains an occurrence of the string reference str ;否则返回 false。

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

该函数在 Qt 4.8 引入。

另请参阅 indexOf () 和 count ().

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

此函数重载 contains ().

Returns true if this string contains an occurrence of the character ch ;否则返回 false。

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

此函数重载 contains ().

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

bool QString:: contains ( QRegExp & rx ) const

此函数重载 contains ().

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

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

该函数在 Qt 4.5 引入。

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

返回 (潜在重叠) 出现数对于字符串 str 在此字符串中。

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

另请参阅 contains () 和 indexOf ().

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

此函数重载 count ().

返回出现数对于字符 ch 在字符串中。

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

此函数重载 count ().

Returns the number of (potentially overlapping) occurrences of the string reference str 在此字符串中。

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

该函数在 Qt 4.8 引入。

另请参阅 contains () 和 indexOf ().

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

此函数重载 count ().

返回次数对于正则表达式 rx 匹配在字符串中。

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

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

int QString:: count () const

此函数重载 count ().

如同 size ().

QChar * QString:: data ()

返回指针指向的数据存储在 QString . The pointer can be used to access and modify the characters that compose the string. For convenience, the data is '\0'-terminated.

范例:

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

Note that the pointer remains valid only as long as the string is not modified by other means. For read-only access, constData () 更快,因为它从不导致 深拷贝 的出现。

另请参阅 constData () 和 operator[] ().

const QChar * QString:: data () const

这是重载函数。

iterator QString:: end ()

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

另请参阅 begin () 和 constEnd ().

const_iterator QString:: end () const

此函数重载 end ().

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

Returns true if the string ends with s ;否则返回 false。

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

QString str = "Bananas";
str.endsWith("anas");         // returns true
str.endsWith("pple");         // returns false
						

另请参阅 startsWith ().

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

此函数重载 endsWith ().

Returns true if the string ends with the string reference s ;否则返回 false。

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

该函数在 Qt 4.8 引入。

另请参阅 startsWith ().

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

此函数重载 endsWith ().

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

Returns true if the string ends with c ;否则返回 false。

此函数重载 endsWith ().

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

将字符串中的每个字符设为字符 ch 。若 size 不同于 -1 (默认),重置字符串大小到 size 事先。

范例:

QString str = "Berlin";
str.fill('z');
// str == "zzzzzz"
str.fill('A', 2);
// str == "AA"
						

另请参阅 resize ().

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

返回 QString 初始采用前 size characters from the string str .

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

Note that, despite the name, this function actually uses the codec defined by QTextCodec::setCodecForCStrings () to convert str to Unicode. Depending on the codec, it may not accept valid US-ASCII (ANSI X3.4-1986) input. If no codec has been set, this function does the same as fromLatin1 ().

另请参阅 toAscii (), fromLatin1 (), fromUtf8 (),和 fromLocal8Bit ().

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

返回 QString 初始采用前 size characters of the Latin-1 string str .

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

另请参阅 toLatin1 (), fromAscii (), fromUtf8 (),和 fromLocal8Bit ().

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

返回 QString 初始采用前 size 个字符对于 8 位字符串 str .

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

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

另请参阅 toLocal8Bit (), fromAscii (), fromLatin1 (),和 fromUtf8 ().

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

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

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

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

QRegExp pattern;
static const QChar unicode[] = {
        0x005A, 0x007F, 0x00A4, 0x0060,
        0x1009, 0x0020, 0x0020};
int size = sizeof(unicode) / sizeof(QChar);
QString str = QString::fromRawData(unicode, size);
if (str.contains(QRegExp(pattern))) {
    // ...
}
						

警告: A string created with fromRawData() is not '\0'-terminated, unless the raw data contains a '\0' character at position size 。这意味着 unicode () will not return a '\0'-terminated string (although utf16 () does, at the cost of copying the raw data).

另请参阅 fromUtf16 () 和 setRawData ().

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

返回副本为 str string. The given string is converted to Unicode using the fromAscii () 函数。

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

另请参阅 fromAscii (), fromLatin1 (), fromLocal8Bit (),和 fromUtf8 ().

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

返回副本为 str string. The given string is assumed to be encoded in utf16 if the size of wchar_t is 2 bytes (e.g. on windows) and ucs4 if the size of wchar_t is 4 bytes (most Unix systems).

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

另请参阅 fromUtf16 (), fromLatin1 (), fromLocal8Bit (), fromUtf8 (),和 fromUcs4 ().

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

返回 QString 初始采用前 size characters of the Unicode string unicode (ISO-10646-UCS-4 encoded).

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

该函数在 Qt 4.2 引入。

另请参阅 toUcs4 (), fromUtf16 (), utf16 (), setUtf16 (),和 fromWCharArray ().

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

返回 QString 初始采用前 size bytes of the UTF-8 string str .

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

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

Non-characters are codepoints that the Unicode standard reserves and must not be used in text interchange. They are the last two codepoints in each Unicode Plane (U+FFFE, U+FFFF, U+1FFFE, U+1FFFF, U+2FFFE, etc.), as well as 16 codepoints in the range U+FDD0..U+FDDF, inclusive.

另请参阅 toUtf8 (), fromAscii (), fromLatin1 (),和 fromLocal8Bit ().

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

返回 QString 初始采用前 size characters of the Unicode string unicode (ISO-10646-UTF-16 encoded).

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

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

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

QString makes a deep copy of the Unicode data.

另请参阅 utf16 () 和 setUtf16 ().

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

返回副本为 string , where the encoding of string depends on the size of wchar. If wchar is 4 bytes, the string is interpreted as ucs-4, if wchar is 2 bytes it is interpreted as ucs-2.

size is -1 (default), the string has to be 0 terminated.

该函数在 Qt 4.2 引入。

另请参阅 fromUtf16 (), fromLatin1 (), fromLocal8Bit (), fromUtf8 (), fromUcs4 (),和 fromStdWString ().

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 找不到。

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

范例:

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
						

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

另请参阅 lastIndexOf (), contains (),和 count ().

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

Returns the index position of the first occurrence of the string str in this string, searching forward from index position from . Returns -1 if str 找不到。

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

范例:

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
						

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

该函数在 Qt 4.5 引入。

另请参阅 lastIndexOf (), contains (),和 count ().

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

此函数重载 indexOf ().

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

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

此函数重载 indexOf ().

Returns the index position of the first occurrence of the string reference str in this string, searching forward from index position from . Returns -1 if str 找不到。

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

该函数在 Qt 4.8 引入。

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

此函数重载 indexOf ().

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

范例:

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

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

此函数重载 indexOf ().

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

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

范例:

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

该函数在 Qt 4.5 引入。

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

插入字符串 str at the given index position 并返回此字符串的引用。

范例:

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

若给定 position 大于 size (), the array is first extended using resize ().

另请参阅 append (), prepend (), replace (),和 remove ().

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

此函数重载 insert ().

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

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

此函数重载 insert ().

Inserts the first size characters of the QChar array unicode at the given index position 在字符串中。

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

此函数重载 insert ().

插入 ch at the given index position 在字符串中。

bool QString:: isEmpty () const

Returns true if the string has no characters; otherwise returns false.

范例:

QString().isEmpty();            // returns true
QString("").isEmpty();          // returns true
QString("x").isEmpty();         // returns false
QString("abc").isEmpty();       // returns false
						

另请参阅 size ().

bool QString:: isNull () const

Returns true if this string is null; otherwise returns false.

范例:

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

Qt makes a distinction between null strings and empty strings for historical reasons. For most applications, what matters is whether or not a string contains any data, and this can be determined using the isEmpty () 函数。

另请参阅 isEmpty ().

bool QString:: isRightToLeft () const

Returns true if the string is read right to left.

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 。若 from is -1 (default), the search starts at the last character; if from is -2, at the next to last character and so on. Returns -1 if str 找不到。

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

范例:

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
						

另请参阅 indexOf (), contains (),和 count ().

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

此函数重载 lastIndexOf ().

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

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

范例:

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
						

该函数在 Qt 4.5 引入。

另请参阅 indexOf (), contains (),和 count ().

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

此函数重载 lastIndexOf ().

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

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

此函数重载 lastIndexOf ().

Returns the index position of the last occurrence of the string reference str in this string, searching backward from index position from 。若 from is -1 (default), the search starts at the last character; if from is -2, at the next to last character and so on. Returns -1 if str 找不到。

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

该函数在 Qt 4.8 引入。

另请参阅 indexOf (), contains (),和 count ().

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

此函数重载 lastIndexOf ().

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

范例:

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

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

此函数重载 lastIndexOf ().

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

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

范例:

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

该函数在 Qt 4.5 引入。

QString QString:: left ( int n ) const

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

返回整个字符串若 n 大于 size () or less than zero.

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

另请参阅 right (), mid (),和 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.

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

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

truncate is true and the size () of the string is more than width , then any characters in a copy of the string after position width are removed, and the copy is returned.

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

另请参阅 rightJustified ().

QStringRef QString:: leftRef ( int n ) const

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

n 大于 size () or less than zero, a reference to the entire string is returned.

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

该函数在 Qt 4.4 引入。

另请参阅 left (), rightRef (), midRef (),和 startsWith ().

int QString:: length () const

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

另请参阅 setLength () 和 resize ().

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

比较 s1 with s2 and returns an integer less than, equal to, or greater than zero if s1 is less than, equal to, or greater than s2 .

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

On Mac OS X since Qt 4.3, this function compares according the "Order for sorted lists" setting in the International prefereces panel.

另请参阅 compare () 和 QTextCodec::locale ().

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

此函数重载 localeAwareCompare ().

Compares this string with the other string and returns an integer less than, equal to, or greater than zero if this string is less than, equal to, or greater than the other 字符串。

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

如同 localeAwareCompare(*this, other) .

该函数在 Qt 4.5 引入。

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

此函数重载 localeAwareCompare ().

比较 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.

该函数在 Qt 4.5 引入。

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

此函数重载 localeAwareCompare ().

Compares this string with the other string and returns an integer less than, equal to, or greater than zero if this string is less than, equal to, or greater than the other 字符串。

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

如同 localeAwareCompare(*this, other) .

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

返回字符串包含 n 个字符对于此字符串,起始于指定 position 索引。

返回 null 字符串若 position index exceeds the length of the string. If there are less than n characters available in the string starting at the given position ,或者若 n is -1 (default), the function returns all characters that are available from the specified position .

范例:

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

另请参阅 left () 和 right ().

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

Returns a substring reference to n 个字符对于此字符串,起始于指定 position .

position exceeds the length of the string, an empty reference is returned.

If there are less than n characters available in the string, starting at the given position ,或者若 n is -1 (default), the function returns all characters from the specified position onwards.

范例:

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

该函数在 Qt 4.4 引入。

另请参阅 mid (), leftRef (),和 rightRef ().

QString QString:: normalized ( NormalizationForm mode ) const

Returns the string in the given Unicode normalization mode .

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

这是重载函数。

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

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

Returns a string equivalent of the number n 根据指定 base .

The base is 10 by default and must be between 2 and 36. For bases other than 10, n is treated as an unsigned integer.

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

另请参阅 setNum ().

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

Returns a string equivalent of the number n , formatted according to the specified format and precision 。见 自变量格式 了解细节。

不像 QLocale::toString (), this function does not honor the user's locale settings.

另请参阅 setNum () 和 QLocale::toString ().

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

这是重载函数。

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

这是重载函数。

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

这是重载函数。

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

这是重载函数。

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

这是重载函数。

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

前置字符串 str to the beginning of this string and returns a reference to this string.

范例:

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

另请参阅 append () 和 insert ().

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

此函数重载 prepend ().

Prepends the Latin-1 string str 到此字符串。

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

此函数重载 prepend ().

前置字节数组 ba to this string. The byte array is converted to Unicode using the fromAscii () 函数。

可以禁用此函数通过定义 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 )

此函数重载 prepend ().

前置字符串 str to this string. The const char pointer is converted to Unicode using the fromAscii () 函数。

可以禁用此函数通过定义 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 )

此函数重载 prepend ().

前置字符 ch 到此字符串。

void QString:: push_back (const QString & other )

This function is provided for STL compatibility, appending the given other string onto the end of this string. It is equivalent to append(other) .

另请参阅 append ().

void QString:: push_back ( QChar ch )

这是重载函数。

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

void QString:: push_front (const QString & other )

This function is provided for STL compatibility, prepending the given other string to the beginning of this string. It is equivalent to prepend(other) .

另请参阅 prepend ().

void QString:: push_front ( QChar ch )

这是重载函数。

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

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

移除 n characters from the string, starting at the given position index, and returns a reference to the string.

若指定 position index is within the string, but position + n is beyond the end of the string, the string is truncated at the specified position .

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

另请参阅 insert () 和 replace ().

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

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

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

范例:

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

这如同 replace(ch, "", cs) .

另请参阅 replace ().

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

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

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

这如同 replace(str, "", cs) .

另请参阅 replace ().

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

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

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

另请参阅 indexOf (), lastIndexOf (),和 replace ().

QString QString:: repeated ( int times ) const

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

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

范例:

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

该函数在 Qt 4.5 引入。

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

替换 n characters beginning at index position 采用字符串 after 并返回此字符串的引用。

范例:

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

另请参阅 insert () 和 remove ().

QString & QString:: replace ( int position , int n , const QChar * unicode , int size )

此函数重载 replace ().

替换 n characters beginning at index position with the first size characters of the QChar array unicode 并返回此字符串的引用。

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

此函数重载 replace ().

替换 n characters beginning at index position with the character after 并返回此字符串的引用。

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

此函数重载 replace ().

Replaces every occurrence of the string before 采用字符串 after 并返回此字符串的引用。

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

范例:

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

注意: The replacement text is not rescanned after it is inserted.

范例:

QString equis = "xxxxxx";
equis.replace("xx", "x");
// equis == "xxx"
						

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

此函数重载 replace ().

Replaces each occurrence in this string of the first blen 字符的 before with the first alen 字符的 after 并返回此字符串的引用。

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

该函数在 Qt 4.5 引入。

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

此函数重载 replace ().

Replaces every occurrence of the character ch in the string with after 并返回此字符串的引用。

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

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

此函数重载 replace ().

Replaces every occurrence of the character before with the character after 并返回此字符串的引用。

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

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

此函数重载 replace ().

Replaces every occurrence of the string before 采用字符串 after 并返回此字符串的引用。

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

注意: The text is not rescanned after a replacement.

该函数在 Qt 4.5 引入。

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

此函数重载 replace ().

Replaces every occurrence of the string before 采用字符串 after 并返回此字符串的引用。

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

注意: The text is not rescanned after a replacement.

该函数在 Qt 4.5 引入。

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

此函数重载 replace ().

Replaces every occurrence of the string before 采用字符串 after 并返回此字符串的引用。

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

注意: The text is not rescanned after a replacement.

该函数在 Qt 4.5 引入。

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

此函数重载 replace ().

Replaces every occurrence of the character c 采用字符串 after 并返回此字符串的引用。

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

注意: The text is not rescanned after a replacement.

该函数在 Qt 4.5 引入。

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

此函数重载 replace ().

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

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

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

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

另请参阅 indexOf (), lastIndexOf (), remove (),和 QRegExp::cap ().

void QString:: reserve ( int size )

试图分配内存为至少 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 maxSize;
bool condition;
QChar nextChar;
result.reserve(maxSize);
while (condition)
    result.append(nextChar);
result.squeeze();
						

另请参阅 squeeze () 和 capacity ().

void QString:: resize ( int size )

Sets the size of the string to size 字符。

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.

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

范例:

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

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

QString t = "Hello";
t += QString(10, 'X');
// t == "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 the leftJustified () 函数:

size 为负,相当于传递 0。

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

另请参阅 truncate () 和 reserve ().

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

返回整个字符串若 n 大于 size () or less than zero.

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

另请参阅 left (), mid (),和 endsWith ().

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

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

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

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

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

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

另请参阅 leftJustified ().

QStringRef QString:: rightRef ( int n ) const

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

n 大于 size () or less than zero, a reference to the entire string is returned.

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

该函数在 Qt 4.4 引入。

另请参阅 right (), leftRef (), midRef (),和 endsWith ().

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 str;
QString csv = "forename,middlename,surname,phone";
QString path = "/usr/local/bin/myapp"; // First field is empty
QString::SectionFlag flag = QString::SectionSkipEmpty;
str = csv.section(',', 2, 2);   // str == "surname"
str = path.section('/', 3, 4);  // str == "bin/myapp"
str = path.section('/', 3, 3, flag); // str == "myapp"
						

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

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

另请参阅 split ().

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

此函数重载 section ().

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

另请参阅 split ().

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

此函数重载 section ().

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

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

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

另请参阅 split () 和 simplified ().

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

Sets the string to the printed value of n 以指定 base , and returns a reference to the string.

The base is 10 by default and must be between 2 and 36. For bases other than 10, n is treated as an unsigned integer.

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

格式始终使用 QLocale::C , i.e., English/UnitedStates. To get a localized string representation of a number, use QLocale::toString () with the appropriate locale.

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

这是重载函数。

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

这是重载函数。

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

这是重载函数。

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

这是重载函数。

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

这是重载函数。

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

这是重载函数。

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

这是重载函数。

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

这是重载函数。

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

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

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

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

这是重载函数。

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

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

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

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

该函数在 Qt 4.7 引入。

另请参阅 fromRawData ().

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

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

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

另请参阅 unicode () 和 setUtf16 ().

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

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

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

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

另请参阅 utf16 () 和 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.

空白意味着任何字符其。 QChar::isSpace () returns true. This includes the ASCII characters '\t', '\n', '\v', '\f', '\r', and ' '.

范例:

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

另请参阅 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 () 和 constData () as arguments to functions that expect '\0'-terminated strings.

范例:

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

另请参阅 isEmpty () 和 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.

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

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

范例:

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

另请参阅 QStringList::join () 和 section ().

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

这是重载函数。

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

这是重载函数。

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;
QStringList list;
str = "Some  text\n\twith  strange whitespace.";
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:

str = "This time, a normal English sentence.";
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:

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

另请参阅 QStringList::join () 和 section ().

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

安全地构建格式化字符串从格式字符串 cformat 和任意自变量列表。

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

注意: This function expects a UTF-8 string for %s and Latin-1 for the format string.

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:

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

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

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

For translations ,尤其当字符串包含多个转义序列时,应考虑使用 arg () 函数代替。这允许翻译者控制置换次序。

另请参阅 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.

另请参阅 reserve () 和 capacity ().

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

Returns true if the string starts with s ;否则返回 false。

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

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

另请参阅 endsWith ().

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

此函数重载 startsWith ().

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

此函数重载 startsWith ().

Returns true if the string starts with c ;否则返回 false。

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

这是重载函数。

Returns true if the string starts with the string reference s ;否则返回 false。

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

该函数在 Qt 4.8 引入。

另请参阅 endsWith ().

void QString:: swap ( QString & other )

交换字符串 other with this string. This operation is very fast and never fails.

该函数在 Qt 4.8 引入。

QByteArray QString:: toAscii () const

Returns an 8-bit 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 ().

Note that, despite the name, this function does not necessarily return an US-ASCII (ANSI X3.4-1986) string and its result may not be US-ASCII compatible.

另请参阅 fromAscii (), toLatin1 (), toUtf8 (), toLocal8Bit (),和 QTextCodec .

QString QString:: toCaseFolded () const

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

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

Returns the string converted to a double 值。

Returns 0.0 if the conversion fails.

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
						

Various string formats for floating point numbers can be converted to double values:

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

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.

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

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

另请参阅 number (), QLocale::setDefault (), QLocale::toDouble (),和 trimmed ().

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

Returns the string converted to a float 值。

If a conversion error occurs, * ok is set to false; otherwise * ok is set to true. Returns 0.0 if the conversion fails.

范例:

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

另请参阅 number (), toDouble (),和 toInt ().

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

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

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

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.

范例:

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
						

另请参阅 number (), toUInt (),和 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. Those characters may be suppressed or replaced with a question mark.

另请参阅 fromLatin1 (), toAscii (), toUtf8 (), toLocal8Bit (),和 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. If the locale encoding could not be determined, this function does the same as toLatin1 ().

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

另请参阅 fromLocal8Bit (), toAscii (), toLatin1 (), toUtf8 (),和 QTextCodec .

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

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

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

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.

范例:

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
						

另请参阅 number (), toULong (),和 toInt ().

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

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

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

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.

范例:

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
						

另请参阅 number (), toULongLong (),和 toInt ().

QString QString:: toLower () const

Returns a lowercase copy of the string.

QString str = "Qt by NOKIA";
str = str.toLower();        // str == "qt by nokia"
						

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

另请参阅 toUpper () 和 QLocale::toLower ().

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

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

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

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.

范例:

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
						

另请参阅 number (), toUShort (),和 toInt ().

std::string QString:: toStdString () const

返回 std::string 对象带有的数据包含在此 QString . The Unicode data is converted into 8-bit characters using the toAscii () 函数。

此运算符主要用于传递 QString 到接受 std::string 对象的函数。

QString contains Unicode characters that the QTextCodec::codecForCStrings () codec cannot handle, using this operator can lead to loss of information.

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

另请参阅 toAscii (), toLatin1 (), toUtf8 (),和 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).

此运算符主要用于传递 QString to a function that accepts a std::wstring object.

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

另请参阅 utf16 (), toAscii (), toLatin1 (), toUtf8 (),和 toLocal8Bit ().

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

Returns the string converted to an 无符号 int 使用基 base , which is 10 by default and must be between 2 and 36, or 0. Returns 0 if the conversion fails.

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

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.

范例:

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
						

另请参阅 number () 和 toInt ().

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

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

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

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.

范例:

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
						

另请参阅 number ().

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

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

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

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.

范例:

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
						

另请参阅 number () 和 toLongLong ().

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

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

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

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.

范例:

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
						

另请参阅 number () 和 toShort ().

QVector < uint > QString:: toUcs4 () const

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

UCS-4 is a Unicode codec and is lossless. All characters from this string can be encoded in UCS-4. The vector is not null terminated.

该函数在 Qt 4.2 引入。

另请参阅 fromUtf8 (), toAscii (), toLatin1 (), toLocal8Bit (), QTextCodec , fromUcs4 (),和 toWCharArray ().

QString QString:: toUpper () const

Returns an uppercase copy of the string.

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

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

另请参阅 toLower () 和 QLocale::toLower ().

QByteArray QString:: toUtf8 () const

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

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

However, in the Unicode range, there are certain codepoints that are not considered characters. The Unicode standard reserves the last two codepoints in each Unicode Plane (U+FFFE, U+FFFF, U+1FFFE, U+1FFFF, U+2FFFE, etc.), as well as 16 codepoints in the range U+FDD0..U+FDDF, inclusive, as non-characters. If any of those appear in the string, they may be discarded and will not appear in the UTF-8 representation, or they may be replaced by one or more replacement characters.

另请参阅 fromUtf8 (), toAscii (), toLatin1 (), toLocal8Bit (),和 QTextCodec .

int QString:: toWCharArray ( wchar_t * array ) const

填充 array with the data contained in this QString object. The array 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).

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

returns the actual length of the string in array .

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

该函数在 Qt 4.2 引入。

另请参阅 utf16 (), toUcs4 (), toAscii (), toLatin1 (), toUtf8 (), toLocal8Bit (),和 toStdWString ().

QString QString:: trimmed () const

返回从开始到结束之间,已移除空白的字符串。

空白意味着任何字符其。 QChar::isSpace () returns true. This includes the ASCII characters '\t', '\n', '\v', '\f', '\r', and ' '.

范例:

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

不像 simplified (),trimmed() 只留下内部空白。

另请参阅 simplified ().

void QString:: truncate ( int position )

截取字符串按给定 position 索引。

若指定 position 索引超出字符串末尾,什么都不发生。

范例:

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

position 为负,相当于传递 0。

另请参阅 chop (), resize (),和 left ().

const QChar * QString:: unicode () const

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

另请参阅 setUnicode () 和 utf16 ().

const ushort * QString:: utf16 () const

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

The returned string is in host byte order.

另请参阅 setUtf16 () 和 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 .

另请参阅 sprintf ().

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

Returns true if this string is not equal to string other ;否则返回 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

此函数重载 operator!= ().

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

此函数重载 operator!= ().

The other byte array is converted to a QString 使用 fromAscii () function. If any NUL characters ('\0') are embedded in the byte array, they will be included in the transformation.

可以禁用此运算符通过定义 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

此函数重载 operator!= ().

The other const char pointer is converted to a QString 使用 fromAscii () 函数。

可以禁用此运算符通过定义 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 )

追加字符串 other onto the end of this string and returns a reference to this string.

范例:

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

This operation is typically very fast ( 常量时间 ),因为 QString preallocates extra space at the end of the string data so it can grow without reallocating the entire string each time.

另请参阅 append () 和 prepend ().

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

此函数重载 operator+= ().

追加 Latin-1 字符串 str 到此字符串。

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

此函数重载 operator+= ().

追加字节数组 ba to this string. The byte array is converted to Unicode using the fromAscii () function. If any NUL characters ('\0') are embedded in the ba byte array, they will be included in the transformation.

可以禁用此函数通过定义 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 )

此函数重载 operator+= ().

追加字符串 str to this string. The const char pointer is converted to Unicode using the fromAscii () 函数。

可以禁用此函数通过定义 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 QStringRef & str )

此函数重载 operator+= ().

Appends the string section referenced by str 到此字符串。

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

此函数重载 operator+= ().

追加字符 ch to this string. The character is converted to Unicode using the fromAscii () 函数。

可以禁用此函数通过定义 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 )

此函数重载 operator+= ().

追加字符 ch to the string.

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

Returns true if this string is lexically less than string other ;否则返回 false。

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

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

此函数重载 operator< ().

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

此函数重载 operator< ().

The other byte array is converted to a QString 使用 fromAscii () function. If any NUL characters ('\0') are embedded in the byte array, they will be included in the transformation.

可以禁用此运算符通过定义 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

此函数重载 operator< ().

The other const char pointer is converted to a QString 使用 fromAscii () 函数。

可以禁用此运算符通过定义 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 ;否则返回 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

此函数重载 operator<= ().

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

此函数重载 operator<= ().

The other byte array is converted to a QString 使用 fromAscii () function. If any NUL characters ('\0') are embedded in the byte array, they will be included in the transformation.

可以禁用此运算符通过定义 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

此函数重载 operator<= ().

The other const char pointer is converted to a QString 使用 fromAscii () 函数。

可以禁用此运算符通过定义 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 )

赋值 other to this string and returns a reference to this string.

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

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

此函数重载 operator= ().

Assigns the Latin-1 string str 到此字符串。

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

此函数重载 operator= ().

赋值 ba to this string. The byte array is converted to Unicode using the fromAscii () function. This function stops conversion at the first NUL character found, or the end of the ba byte array.

可以禁用此运算符通过定义 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 )

此函数重载 operator= ().

赋值 str to this string. The const char pointer is converted to Unicode using the fromAscii () 函数。

可以禁用此运算符通过定义 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 )

此函数重载 operator= ().

Assigns character ch to this string. The character is converted to Unicode using the fromAscii () 函数。

可以禁用此运算符通过定义 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 )

此函数重载 operator= ().

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

此函数重载 operator== ().

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

此函数重载 operator== ().

The other byte array is converted to a QString 使用 fromAscii () function. This function stops conversion at the first NUL character found, or the end of the byte array.

可以禁用此运算符通过定义 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

此函数重载 operator== ().

The other const char pointer is converted to a QString 使用 fromAscii () 函数。

可以禁用此运算符通过定义 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 ;否则返回 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

此函数重载 operator> ().

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

此函数重载 operator> ().

The other byte array is converted to a QString 使用 fromAscii () function. If any NUL characters ('\0') are embedded in the byte array, they will be included in the transformation.

可以禁用此运算符通过定义 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

此函数重载 operator> ().

The other const char pointer is converted to a QString 使用 fromAscii () 函数。

可以禁用此运算符通过定义 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 ;否则返回 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

此函数重载 operator>= ().

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

此函数重载 operator>= ().

The other byte array is converted to a QString 使用 fromAscii () function. If any NUL characters ('\0') are embedded in the byte array, they will be included in the transformation.

可以禁用此运算符通过定义 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

此函数重载 operator>= ().

The other const char pointer is converted to a QString 使用 fromAscii () 函数。

可以禁用此运算符通过定义 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 position )

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

范例:

QString str;
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.

另请参阅 at ().

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

此函数重载 operator[] ().

QCharRef QString:: operator[] ( uint position )

此函数重载 operator[] ().

Returns the character at the specified position in the string as a modifiable reference. Equivalent to at(position) .

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

此函数重载 operator[] ().

相关非成员

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

返回 true 若 s1 不等于 s2 ;否则返回 false。

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

另请参阅 QString::compare ().

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

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

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

Returns a string which is the result of concatenating s1 and s2 ( s2 is converted to Unicode using the QString::fromAscii () 函数)。

另请参阅 QString::fromAscii ().

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

Returns a string which is the result of concatenating s1 and s2 ( s1 is converted to Unicode using the QString::fromAscii () 函数)。

另请参阅 QString::fromAscii ().

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

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

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

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

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

返回 true 若 s1 is lexically less than s2 ; otherwise returns false. For s1 != 0, this is equivalent to compare(s1, s2) < 0 .

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

另请参阅 QString::compare ().

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

写入给定 string 到指定 stream .

另请参阅 序列化 Qt 数据类型 .

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

返回 true 若 s1 is lexically less than or equal to s2 ; otherwise returns false. For s1 != 0, this is equivalent to compare(s1, s2) <= 0 .

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

另请参阅 QString::compare ().

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

此函数重载 operator== ().

返回 true 若 s1 等于 s2 ; otherwise returns false. Note that no string is equal to s1 being 0.

相当于 s1 != 0 && compare(s1, s2) == 0 .

另请参阅 QString::compare ().

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

返回 true 若 s1 is lexically greater than s2 ; otherwise returns false. Equivalent to compare(s1, s2) > 0 .

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

另请参阅 QString::compare ().

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

返回 true 若 s1 is lexically greater than or equal to s2 ; otherwise returns false. For s1 != 0, this is equivalent to compare(s1, s2) >= 0 .

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

QDataStream & operator>> ( QDataStream & stream , QString & string )

读取字符串从指定 stream 进给定 string .

另请参阅 序列化 Qt 数据类型 .

宏文档编制

QT_NO_CAST_FROM_ASCII

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

另请参阅 QT_NO_CAST_TO_ASCII and QT_NO_CAST_FROM_BYTEARRAY .

QT_NO_CAST_TO_ASCII

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

另请参阅 QT_NO_CAST_FROM_ASCII and QT_NO_CAST_FROM_BYTEARRAY .