QString 類

QString 類提供 Unicode 字符串。 更多...

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

此類 強烈可比較 .

此類 強烈可比較 with QChar , QLatin1StringView , const char16_t *, QStringView ,和 QUtf8StringView .

此類 強烈可比較 with QByteArray , QByteArrayView ,和 const char *。

當比較字節數組時,它們的內容會被解釋成 UTF-8。

注意: 此類的所有函數 可重入 .

公共類型

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

公共函數

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

靜態公共成員

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

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

詳細描述

QString 存儲字符串的 16 位 QChar ,其中各 QChar 相當於一 UTF-16 編碼單元 (代碼值大於 65535 的 Unicode 字符是使用代理對存儲的,也就是說,2 連續 QChar )。

Unicode 是支持當今使用的大多數書寫係統的國際標準。它是 US-ASCII (ANSI X3.4-1986) 和 Latin-1 (ISO 8859-1) 的超集,且所有 US-ASCII/Latin-1 字符可用於相同代碼位置。

在幕後,QString 使用 隱式共享 (寫時拷貝) 以縮減內存用量並避免不必要的數據拷貝。這還有助於縮減存儲 16 位字符而不是 8 位字符的固有開銷。

除 QString 外,Qt 還提供 QByteArray 類來存儲原生字節和以 \0 結尾的傳統 8 位字符串。對於大多數目的,QString 是想要使用的類。縱觀 Qt API 和 Unicode 支持的用法,可確保應用程序易於翻譯,若在某個時刻想要擴展應用程序市場。2 突齣案例 QByteArray 是閤適的,當需要存儲原生二進製數據時,和當內存守恒臨界時 (像在嵌入式係統)。

初始化字符串

初始化 QString 的一種方式是傳遞 const char * 到其構造函數。例如,以下代碼創建包含數據 Hello 大小為 5 的 QString:

QString str = "Hello";
					

QString 轉換 const char * 數據成 Unicode 使用 fromUtf8 () 函數。

QString 的所有函數都接受 const char * 參數, const char * 被解釋成經典 C 樣式 '\\0' 結尾字符串。除函數名明顯指示某些其它編碼外,這種 const char * 參數被假定為按 UTF-8 編碼。

還可以將字符串數據提供成數組化的 QChar

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

QString 製作深拷貝對 QChar 數據,所以可以稍後修改它,經驗上無副作用。可以避免對字符數據進行深拷貝通過使用 QStringView or QString::fromRawData () 代替。

另一種方式是設置字符串大小使用 resize () 並逐字符初始化數據。QString 使用基於 0 的索引,就像 C++ 數組。要訪問位於特定索引位置的字符,可以使用 operator[] ()。對於非 const 字符串, 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 (qsizetype i = 0; i < str.size(); ++i) {
    if (str.at(i) >= QChar('a') && str.at(i) <= QChar('f'))
        qDebug() << "Found character in range [a-f]";
}
					

The at () 函數可以更快相比 operator[] () 因為它從不導緻 深拷貝 的齣現。另外,使用 first (), last (),或 sliced () 函數能一次提取幾個字符。

QString 可以嵌入 \0 字符 ( QChar::Null )。 size () 函數始終返迴整個字符串的大小,包括嵌入 \0 字符。

後於調用 resize () 函數,新近分配字符擁有未定義值。要把字符串中的所有字符設為特定值,使用 fill () 函數。

QString 提供瞭很多設計用於簡化字符串用法的重載。例如,若想要比較 QString 與字符串文字,可以像這樣編寫代碼且它會如期望般工作:

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

還可以把字符串文字傳遞給接受 QString 作為自變量的函數,援引 QString(const char *) 構造函數。同樣,可以傳遞 QString 的函數接受 const char * 自變量使用 qPrintable () 宏,返迴給定 QString 如 const char * 。這相當於調用 toLocal8Bit (). constData () on the QString.

操縱字符串數據

QString 提供修改字符數據的基本功能: 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"
					

在以上範例中, replace () 函數的前 2 自變量是從哪裏開始替換的位置,和應替換的字符數。

當數據修改函數遞增字符串大小時,QString 可能重新分配保持其數據的內存。當這發生時,QString 會立即超齣它所需要的進行擴展,以便擁有進一步的擴展空間而不用重新分配,直到字符串大小有顯著遞增。

The insert (), remove (),和當采用不同大小的字符串替換子字符串時, replace () 函數可能很慢 ( 綫性時間 ) 對於大字符串,因為它們要求把字符串中的很多字符,在內存中至少移動一個位置。

若正逐步構建 QString 且提前大概知道 QString 將包含多少個字符,可以調用 reserve (),要求 QString 預分配一定數量的內存。也可以調用 capacity () 以找齣 QString 實際有分配多少內存。

QString 提供 STL 樣式迭代器 ( QString::const_iterator and QString::iterator ). In practice, iterators are handy when working with generic algorithms provided by the C++ standard library.

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

注意: 由於 隱式共享 , the first non- const operator or function used on a given QString may cause it to internally perform a deep copy of its data. This invalidates all iterators over the string and references to individual characters within it. Do not call non-const functions while keeping iterators. Accessing an iterator or reference after it has been invalidated leads to undefined behavior. See the 隱式共享迭代器問題 section for more information.

A frequent requirement is to remove or simplify the spacing between visible characters in a string. The characters that make up that spacing are those for which isSpace () 返迴 true , such as the simple space ' ' , the horizontal tab '\\t' and the newline '\\n' . To obtain a copy of a string leaving out any spacing from its start and end, use trimmed (). To also replace each sequence of spacing characters within the string with a simple space, ' ' ,使用 simplified ().

若想要查找 QString 中的特定字符 (或子字符串) 的所有齣現,使用 indexOf () 或 lastIndexOf () functions.The former searches forward, the latter searches backward. Either can be told an index position from which to start their search. Each returns the index position of the character or substring if they find it; otherwise, they return -1. For example, here is a typical loop that finds all occurrences of a particular substring:

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

QString 提供瞭很多按數字轉換成字符串,和把字符串轉換成數字的函數。見 arg () 函數, setNum () 函數, number () 靜態函數,和 toInt (), toDouble (),及類似函數。

要獲取字符串的大寫 (或小寫) 版本,使用 toUpper () 或 toLower ().

字符串列錶的處理是通過 QStringList 類。可以把字符串分割成字符串列錶使用 split () 函數,和把字符串列錶聯接成單字符串采用可選分隔符使用 QStringList::join (). You can obtain a filtered list from a string list by selecting the entries in it that contain a particular substring or match a particular QRegularExpression 。見 QStringList::filter () 瞭解細節。

查詢字符串數據

要看 QString 是否以特定子字符串開頭 (或結尾),使用 startsWith () 或 endsWith ()。要校驗 QString 是否包含特有字符 (或子字符串),使用 contains () function. To find out how many times a particular character or substring occurs in a string, use count().

要獲得實際字符數據指針,調用 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.

比較字符串

可以比較 QString 使用重載運算符譬如 operator< (), operator<= (), operator== (), operator>= (), and so on. The comparison is based exclusively on the lexicographical order of the two strings, seen as sequences of UTF-16 code units. It is very fast but is not what a human would expect; the QString::localeAwareCompare () function is usually a better choice for sorting user-interface strings, when such a comparison is available.

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

  • 在 Windows, localeAwareCompare () uses the current user locale, as set in the regional and 語言 選項屬於 控製麵闆 .
  • 在 macOS 和 iOS, localeAwareCompare () compares according to the Order for sorted lists setting in the 國際化首選項 麵闆。
  • On other Unix-like systems, the comparison falls back to the system library's strcoll() .

在編碼字符串數據和 QString 之間轉換

QString 提供的下列函數返迴 const char * 版本的字符串如 QByteArray : toUtf8 (), toLatin1 (),和 toLocal8Bit ().

  • toLatin1 () 返迴 Latin-1 (ISO 8859-1) 編碼 8 位字符串。
  • toUtf8 () 返迴 UTF-8 編碼 8 位字符串。UTF-8 是 US-ASCII (ANSI X3.4-1986) 超集,支持透過多字節序列的整個 Unicode 字符集。
  • toLocal8Bit () 返迴使用係統區域設置編碼的 8 位字符串。這如同 toUtf8 () 在 Unix 係統。

要轉換自這些編碼之一,QString 提供 fromLatin1 (), fromUtf8 (),和 fromLocal8Bit ()。其它編碼的支持是透過 QStringEncoder and QStringDecoder 類。

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

You then need to explicitly call fromUtf8 (), fromLatin1 (),或 fromLocal8Bit () to construct a QString from an 8-bit string, or use the lightweight QLatin1StringView 類。例如:

// Required for using the '_L1' string literal.
using namespace Qt::StringLiterals;
// ...
QString url = "https://www.unicode.org/"_L1;
					

同樣,必須調用 toLatin1 (), toUtf8 (),或 toLocal8Bit () 明確把 QString 轉換成 8 位字符串。

C 程序員注意事項
由於 C++ 類型係統和 QString 實際為 隱式共享 ,可以視 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 null and empty strings. A null string is a string that is initialized using QString's default constructor or by passing nullptr 到構造函數。 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, toUtf8 (). constData () 返迴有效指針 (不是 nullptr ) to a '\0' character for a null string. We recommend that you always use the isEmpty () function and avoid isNull ().

數字格式

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

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

浮點格式

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

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

更高效的字符串構造

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

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

// Required for using the '_L1' string literal.
using namespace Qt::StringLiterals;
// ...
    QString foo;
    QString type = "long";
    foo = "vector<"_L1 + type + ">::iterator"_L1;
    if (foo.startsWith("(" + type + ") 0x"))
        ...
					

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

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

These allocations can be optimized by an internal class QStringBuilder . This class is marked internal and does not appear in the documentation, because you aren't meant to instantiate it in your code. Its use will be automatic, as described below. The class is found in src/corelib/tools/qstringbuilder.cpp if you want to have a look at it.

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

Additional efficiency is gained by inlining and reducing reference counting (the QString created from a QStringBuilder has a ref count of 1, whereas QString::append () 需要額外測試)。

There are two ways you can access this improved method of string construction. The straightforward way is to include QStringBuilder wherever you want to use it and use the '%' 運算符而不是 '+' 當串聯字符串時:

    #include <QStringBuilder>
    QString hello("hello");
    QStringView el = QStringView{ hello }.mid(2, 3);
    QLatin1StringView world("world");
    QString message =  hello % el % world % QChar('!');
					

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

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

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

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

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

最大尺寸和內存不足情況

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

當內存分配失敗時,QString 拋齣 std::bad_alloc exception if the application was compiled with exception support. Out-of-memory conditions in Qt containers are the only cases where Qt will throw exceptions. If exceptions are disabled, then running out of memory is undefined behavior.

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

另請參閱 fromRawData (), QChar , QStringView , QLatin1StringView ,和 QByteArray .

成員類型文檔編製

QString:: ConstIterator

Qt 樣式同義詞 QString::const_iterator .

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

QString:: const_iterator

另請參閱 QString::iterator .

QString:: const_pointer

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

QString:: const_reference

QString:: const_reverse_iterator

另請參閱 QString::reverse_iterator and QString::const_iterator .

QString:: difference_type

QString:: iterator

另請參閱 QString::const_iterator .

QString:: pointer

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

QString:: reference

QString:: reverse_iterator

另請參閱 QString::const_reverse_iterator and QString::iterator .

QString:: size_type

QString:: value_type

成員函數文檔編製

QString QString:: left ( qsizetype n ) &&

QString QString:: left ( qsizetype n ) const &

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

若知道 n 不可以超齣邊界,使用 first () 代替在新代碼中,因為它更快。

返迴整個字符串若 n >= size (),或小於 0。

另請參閱 first (), last (), startsWith (), chopped (), chop (),和 truncate ().

QString QString:: right ( qsizetype n ) const &

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

若知道 n 不可以超齣邊界,使用 last () 代替在新代碼中,因為它更快。

返迴整個字符串若 n >= size (),或小於 0。

另請參閱 endsWith (), last (), first (), sliced (), chopped (), chop (), truncate (),和 slice ().

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

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

返迴字符串包含 n 個字符對於此字符串,起始於指定 position 索引。

若知道 position and n 不可以超齣邊界,使用 sliced () 代替在新代碼中,因為它更快。

返迴 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 .

另請參閱 first (), last (), sliced (), chopped (), chop (), truncate (),和 slice ().

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

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

返迴字符串包含前 n 個字符對於此字符串。

注意: 行為未定義當 n < 0 or n > size ().

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

該函數在 Qt 6.0 引入。

另請參閱 last (), sliced (), startsWith (), chopped (), chop (), truncate (),和 slice ().

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

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

返迴的字符串包含最後 n 個字符對於此字符串。

注意: 行為未定義當 n < 0 or n > size ().

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

該函數在 Qt 6.0 引入。

另請參閱 first (), sliced (), endsWith (), chopped (), chop (), truncate (),和 slice ().

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

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

返迴字符串包含 n characters of this string, starting at position pos .

注意: 行為未定義當 pos < 0, n < 0, or pos + n > size ().

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

該函數在 Qt 6.0 引入。

另請參閱 first (), last (), chopped (), chop (), truncate (),和 slice ().

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

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

這是重載函數。

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

注意: 行為未定義當 pos < 0 or pos > size ().

該函數在 Qt 6.0 引入。

另請參閱 first (), last (), chopped (), chop (), truncate (),和 slice ().

QString QString:: chopped ( qsizetype len ) &&

QString QString:: chopped ( qsizetype len ) const &

返迴字符串包含 size () - len leftmost characters of this string.

注意: 行為未定義若 len 為負或大於 size ().

另請參閱 endsWith (), first (), last (), sliced (), chop (), truncate (),和 slice ().

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

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

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

該函數在 Qt 6.8 引入。

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

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

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

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

另請參閱 QString::arg ().

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

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

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

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

相當於

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

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

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

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

QStringTokenizer result = sv.tokenize(sep);
					

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

auto result = sv.tokenize(sep);
					

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

該函數在 Qt 6.0 引入。

注意: (1) is noexcept when noexcept(qTokenize(std::declval<QString>(), std::forward<Needle>(needle), flags...)) is true .

注意: (2) is noexcept when noexcept(qTokenize(std::declval<const QString &>(), std::forward<Needle>(needle), flags...)) is true .

注意: (3) is noexcept when noexcept(qTokenize(std::declval<const QString>(), std::forward<Needle>(needle), flags...)) is true .

另請參閱 QStringTokenizer and qTokenize ().

[constexpr noexcept] QString:: QString ()

構造 null 字符串。認為 null 字符串也為空。

另請參閱 isEmpty (), isNull (),和 null 和空字符串之間的區彆 .

QString:: QString ( QChar ch )

Constructs a string of size 1 containing the character ch .

QString:: QString ( QLatin1StringView str )

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

另請參閱 fromLatin1 ().

[explicit, since 6.8] QString:: QString ( QStringView sv )

Constructs a string initialized with the string view's data.

The QString will be null if and only if sv 為 null。

該函數在 Qt 6.8 引入。

另請參閱 fromUtf16 ().

QString:: QString (const QByteArray & ba )

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

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

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

另請參閱 fromLatin1 (), fromLocal8Bit (),和 fromUtf8 ().

QString:: QString (const char * str )

Constructs a string initialized with the 8-bit string str . The given const char pointer is converted to Unicode using the fromUtf8 () 函數。

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.

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

另請參閱 fromLatin1 (), fromLocal8Bit (),和 fromUtf8 ().

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

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

該函數在 Qt 6.1 引入。

另請參閱 fromLatin1 (), fromLocal8Bit (),和 fromUtf8 ().

[explicit] QString:: QString (const QChar * unicode , qsizetype size = -1)

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

unicode 為 0,構造 null 字符串。

size 為負, unicode is assumed to point to a '\0'-terminated array and its length is determined dynamically. The terminating null character is not considered part of the string.

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

另請參閱 fromRawData ().

QString:: QString ( qsizetype size , QChar ch )

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

另請參閱 fill ().

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

構造副本為 other .

此操作花費 常量時間 ,因為 QString 是 隱式共享 . 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= ().

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

Move-constructs a QString instance, making it point at the same object that other 所指嚮的。

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

此函數重載 append()。

追加字符 ch 到此字符串。

QString &QString:: append ( QLatin1StringView str )

此函數重載 append()。

追加 Latin-1 字符串視圖通過 str 到此字符串。

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

此函數重載 append()。

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

該函數在 Qt 6.0 引入。

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

此函數重載 append()。

追加 UTF-8 字符串視圖 str 到此字符串。

該函數在 Qt 6.5 引入。

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

此函數重載 append()。

追加字節數組 ba to this string. The given byte array is converted to Unicode using the fromUtf8 () 函數。

可以禁用此函數通過定義 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 fromUtf8 () 函數。

可以禁用此函數通過定義 QT_NO_CAST_FROM_ASCII when you compile your applications. This can be useful if you want to ensure that all user-visible strings go through QObject::tr (), for example.

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

此函數重載 append()。

追加 len 字符來自 QChar array str 到此字符串。

QString QString:: arg (const QString & a , int fieldWidth = 0, QChar fillChar = u' ') 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 asprintf () is that the order of the numbered place markers can change, if the application's strings are translated into other languages, but each arg() will still replace the lowest numbered unreplaced place marker, no matter where it appears. Also, if place marker %i appears more than once in the string, the arg() replaces all of them.

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

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

此函數重載 arg()。

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

這是重載函數。

Returns a copy of this string with the lowest-numbered place-marker replaced by the Latin-1 string viewed by a ,即: %1 , %2 , ..., %99 .

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

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

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

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

這是重載函數。

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

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

此範例展示如何創建 status 字符串為處理文件列錶時報告進度:

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

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

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

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

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

此函數重載 arg()。

The a 自變量被解釋成 Latin-1 字符。

QString QString:: arg ( int a , int fieldWidth = 0, int base = 10, QChar fillChar = u' ') 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 system locale is used. The 'L' flag is ignored if base is not 10.

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

另請參閱 Number Formats .

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

另請參閱 Number Formats .

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

另請參閱 Number Formats .

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

另請參閱 Number Formats .

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

另請參閱 Number Formats .

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

另請參閱 Number Formats .

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

另請參閱 Number Formats .

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

另請參閱 Number Formats .

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

此函數重載 arg()。

自變量 a is formatted according to the specified format and precision 。見 Floating-point Formats 瞭解細節。

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"
					

另請參閱 QLocale::toString (), QLocale::FloatingPointPrecisionOption ,和 Number Formats .

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

安全地構建格式化字符串從格式字符串 cformat 和任意自變量列錶。

格式字符串支持轉換說明符、長度修飾符及由標準 C++ 庫 printf() 提供的標誌。 cformat 字符串和 %s 自變量必須是 UTF-8 編碼。

注意: The %lc 轉義序列期望 unicode 字符類型為 char16_t ,或 ushort (如返迴通過 QChar::unicode ())。 %ls 轉義序列期望的指針指嚮以 0 結尾的數組的 Unicode 字符類型為 char16_t ,或 ushort (如返迴通過 QString::utf16 ())。這與標準 C++ 庫 printf() 不一緻,後者定義的 %lc 會打印 wchar_t 而 %ls 會打印 wchar_t* ,且平颱還可能産生編譯器警告,若大小請考慮使用請考慮使用請考慮使用請考慮使用請考考慮 wchar_t 不是 16 位。

警告: 不推薦在新 Qt 代碼中使用 QString::asprintf()。取而代之,考慮使用 QTextStream or arg (),兩者無縫支持 Unicode 字符串且是類型安全的。這裏的範例使用 QTextStream :

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

For translations ,尤其當字符串包含多個轉義序列時,應考慮使用 arg () 函數代替。這允許翻譯者控製置換次序。

另請參閱 arg ().

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

替換此字符串的內容采用副本 v 並返迴此字符串的引用。

此字符串的大小將等於大小對於 v ,轉換成 UTF-16 就像通過 v.toString() 。不像 QAnyStringView::toString (), however, this function only allocates memory if the estimated size exceeds the capacity of this string or this string is shared.

該函數在 Qt 6.6 引入。

另請參閱 QAnyStringView::toString ().

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

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

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

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

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

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

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

該函數在 Qt 6.6 引入。

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

替換此字符串的內容以 n 個副本對於 c 並返迴此字符串的引用。

此字符串的大小將等於 n ,必須非負。

此函數將隻分配內存若 n 超過此字符串的容量 (或此字符串是共享的)。

該函數在 Qt 6.6 引入。

另請參閱 fill ().

const QChar QString:: at ( qsizetype position ) const

返迴字符按給定索引 position 在字符串中。

The position 在字符串中必須是有效索引位置 (即 0 <= position < size ()).

另請參閱 operator[] ().

QChar &QString:: back ()

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

此函數為兼容 STL (標準模闆庫) 提供。

警告: 在空字符串調用此函數,將構成未定義行為。

另請參閱 front (), at (),和 operator[] ().

QChar QString:: back () const

返迴字符串中的最後一個字符。如同 at(size() - 1) .

此函數為兼容 STL (標準模闆庫) 提供。

警告: 在空字符串調用此函數,將構成未定義行為。

另請參閱 front (), at (),和 operator[] ().

QString::iterator QString:: begin ()

返迴 STL 樣式迭代器 指嚮字符串中的首個字符。

警告: 返迴迭代器不驗證當分離時或當 QString 被修改。

另請參閱 constBegin () 和 end ().

QString::const_iterator QString:: begin () const

此函數重載 begin()。

qsizetype QString:: capacity () const

Returns the maximum number of characters that can be stored in the string without forcing a reallocation.

The sole purpose of this function is to provide a means of fine tuning QString 's memory usage. In general, you will rarely ever need to call this function. If you want to know how many characters are in the string, call size ().

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

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

另請參閱 reserve () 和 squeeze ().

QString::const_iterator QString:: cbegin () const

返迴常量 STL 樣式迭代器 指嚮字符串中的首個字符。

警告: 返迴迭代器不驗證當分離時或當 QString 被修改。

另請參閱 begin () 和 cend ().

QString::const_iterator QString:: cend () const

返迴常量 STL 樣式迭代器 僅僅指嚮字符串中最後一個字符的後麵。

警告: 返迴迭代器不驗證當分離時或當 QString 被修改。

另請參閱 cbegin () 和 end ().

void QString:: chop ( qsizetype n )

移除 n 個字符從字符串末尾起。

n >= size (),結果為空字符串;若 n 為負,相當於傳遞 0。

範例:

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

若想要移除字符從 beginning 對於字符串,使用 remove () 代替。

另請參閱 truncate (), resize (), remove (),和 QStringView::chop ().

void QString:: clear ()

清零字符串內容,並使之為 null。

另請參閱 resize () 和 isNull ().

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

比較字符串 s1 采用字符串 s2 並返迴負整數若 s1 小於 s2 ,正整數若大於 s2 ,和 0 若它們相等。

cs is Qt::CaseSensitive (默認),比較區分大小寫;否則,比較不區分大小寫。

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
					

注意: This function treats null strings the same as empty strings, for more details see null 和空字符串之間的區彆 .

另請參閱 operator== (), operator< (), operator> (),和 Comparing Strings .

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

此函數重載 compare()。

履行比較為此與 ch ,使用區分大小寫設置 cs .

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

此函數重載 compare()。

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

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

此函數重載 compare()。

履行比較為此與 s ,使用區分大小寫設置 cs .

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

此函數重載 compare()。

詞法上比較此字符串與字符串 other 並返迴負整數若此字符串小於 other ,正整數若大於 other ,和 0 若它們相等。

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

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

此函數重載 compare()。

履行比較為 s1 and s2 ,使用區分大小寫設置 cs .

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

此函數重載 compare()。

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

此函數重載 compare()。

履行比較為 s1 and s2 ,使用區分大小寫設置 cs .

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

此函數重載 compare()。

QString::const_iterator QString:: constBegin () const

返迴常量 STL 樣式迭代器 指嚮字符串中的首個字符。

警告: 返迴迭代器不驗證當分離時或當 QString 被修改。

另請參閱 begin () 和 constEnd ().

const QChar *QString:: constData () const

返迴指針指嚮的數據存儲在 QString . The pointer can be used to access the characters that compose the string.

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

注意: 返迴字符串不能以 \0 結尾。使用 size () 以確定數組的長度。

另請參閱 data (), operator[] (),和 fromRawData ().

QString::const_iterator QString:: constEnd () const

返迴常量 STL 樣式迭代器 僅僅指嚮字符串中最後一個字符的後麵。

警告: 返迴迭代器不驗證當分離時或當 QString 被修改。

另請參閱 constBegin () 和 end ().

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

返迴 true 若正則錶達式 re 匹配此字符串中的某些地方;否則返迴 false .

若匹配成功且 rmatch 不是 nullptr ,它還把匹配結果寫入 QRegularExpressionMatch 對象指嚮的 rmatch .

另請參閱 QRegularExpression::match ().

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

返迴 true 若此字符串包含齣現的字符串 str ;否則返迴 false .

cs is Qt::CaseSensitive (默認),搜索區分大小寫;否則,搜索不區分大小寫。

範例:

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

另請參閱 indexOf () 和 count ().

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

此函數重載 contains()。

返迴 true 若此字符串包含齣現字符 ch ;否則返迴 false .

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

此函數重載 contains()。

返迴 true 若此字符串包含齣現的 latin-1 字符串 str ;否則返迴 false .

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

此函數重載 contains()。

返迴 true 若此字符串包含齣現的字符串視圖 str ;否則返迴 false .

cs is Qt::CaseSensitive (默認),搜索區分大小寫;否則,搜索不區分大小寫。

另請參閱 indexOf () 和 count ().

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

返迴 (潛在重疊) 齣現數對於字符串 str 在此字符串中。

cs is Qt::CaseSensitive (默認),搜索區分大小寫;否則,搜索不區分大小寫。

另請參閱 contains () 和 indexOf ().

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

此函數重載 count()。

返迴次數對於正則錶達式 re 匹配在字符串中。

由於曆史原因,此函數計算重疊匹配,因此下文範例有 4 個 ana 或 ama 實例:

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

此行為不同於簡單遍曆字符串中的匹配使用 QRegularExpressionMatchIterator .

另請參閱 QRegularExpression::globalMatch ().

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

此函數重載 count()。

返迴齣現數對於字符 ch 在字符串中。

cs is Qt::CaseSensitive (默認),搜索區分大小寫;否則,搜索不區分大小寫。

另請參閱 contains () 和 indexOf ().

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

此函數重載 count()。

返迴 (潛在重疊) 齣現數對於字符串視圖 str 在此字符串中。

cs is Qt::CaseSensitive (默認),搜索區分大小寫;否則,搜索不區分大小寫。

該函數在 Qt 6.0 引入。

另請參閱 contains () 和 indexOf ().

QString::const_reverse_iterator QString:: crbegin () const

返迴常量 STL-style reverse iterator pointing to the first character in the string, in reverse order.

警告: 返迴迭代器不驗證當分離時或當 QString 被修改。

另請參閱 begin (), rbegin (),和 rend ().

QString::const_reverse_iterator QString:: crend () const

返迴常量 STL-style reverse iterator pointing just after the last character in the string, in reverse order.

警告: 返迴迭代器不驗證當分離時或當 QString 被修改。

另請參閱 end (), rend (),和 rbegin ().

QChar *QString:: data ()

返迴指針指嚮的數據存儲在 QString . The pointer can be used to access and modify the characters that compose the string.

不像 constData () 和 unicode (),返迴數據始終以 \0 結尾。

範例:

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

這是重載函數。

注意: 返迴字符串不能以 \0 結尾。使用 size () 以確定數組的長度。

另請參閱 fromRawData ().

QString::iterator QString:: end ()

返迴 STL 樣式迭代器 僅僅指嚮字符串中最後一個字符的後麵。

警告: 返迴迭代器不驗證當分離時或當 QString 被修改。

另請參閱 begin () 和 constEnd ().

QString::const_iterator QString:: end () const

此函數重載 end()。

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

返迴 true 若字符串結尾為 s ;否則返迴 false .

cs is Qt::CaseSensitive (默認),搜索區分大小寫;否則,搜索不區分大小寫。

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

另請參閱 startsWith ().

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

返迴 true 若字符串結尾為 c ;否則返迴 false .

此函數重載 endsWith()。

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

此函數重載 endsWith()。

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

此函數重載 endsWith()。

返迴 true 若字符串結尾為字符串視圖 str ;否則返迴 false .

cs is Qt::CaseSensitive (默認),搜索區分大小寫;否則,搜索不區分大小寫。

另請參閱 startsWith ().

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

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

該函數在 Qt 6.1 引入。

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

這是重載函數。

移除錶示字符 it 從字符串。返迴迭代器到立即擦除字符後的字符。

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

該函數在 Qt 6.5 引入。

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

將字符串中的每個字符設為字符 ch 。若 size 不同於 -1 (默認),重置字符串大小到 size 事先。

範例:

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

另請參閱 resize ().

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

構造新的 QString 包含副本 string CFString.

注意: 此函數隻可用於 macOS 和 iOS。

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

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

該函數在 Qt 6.6 引入。

另請參閱 toEcmaString ().

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

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

size is -1 , strlen(str) 被使用,取而代之。

另請參閱 toLatin1 (), fromUtf8 (),和 fromLocal8Bit ().

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

這是重載函數。

返迴 QString 初始采用 Latin-1 字符串 str .

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

該函數在 Qt 6.0 引入。

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

這是重載函數。

返迴 QString 初始采用 Latin-1 字符串 str .

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

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

返迴 QString 初始采用前 size 個字符對於 8 位字符串 str .

size is -1 , strlen(str) 被使用,取而代之。

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

另請參閱 toLocal8Bit (), fromLatin1 (),和 fromUtf8 ().

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

這是重載函數。

返迴 QString initialized with the 8-bit string str .

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

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

該函數在 Qt 6.0 引入。

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

這是重載函數。

返迴 QString initialized with the 8-bit string str .

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

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

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

構造新的 QString 包含副本 string NSString.

注意: 此函數隻可用於 macOS 和 iOS。

[static] QString QString:: fromRawData (const QChar * unicode , qsizetype 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 is an example of how we can use a QRegularExpression on raw data in memory without requiring to copy the data into a QString :

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

警告: 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 assumed to be encoded in UTF-8, and is converted to QString 使用 fromUtf8 () 函數。

另請參閱 fromLatin1 (), fromLocal8Bit (), fromUtf8 (),和 QByteArray::fromStdString ().

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

返迴副本為 str string. The given string is assumed to be encoded in UTF-16, and is converted to QString 使用 fromUtf16 () 函數。

另請參閱 fromUtf16 (), fromStdWString (),和 fromStdU32String ().

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

返迴副本為 str string. The given string is assumed to be encoded in UTF-32, and is converted to QString 使用 fromUcs4 () 函數。

另請參閱 fromUcs4 (), fromStdWString (),和 fromStdU16String ().

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

另請參閱 fromUtf16 (), fromLatin1 (), fromLocal8Bit (), fromUtf8 (), fromUcs4 (), fromStdU16String (),和 fromStdU32String ().

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

返迴 QString 初始采用前 size characters of the Unicode string unicode (encoded as UTF-32).

size is -1 (default), unicode must be '\0'-terminated.

另請參閱 toUcs4 (), fromUtf16 (), utf16 (), setUtf16 (), fromWCharArray (),和 fromStdU32String ().

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

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

size is -1 , strlen(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.

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

另請參閱 toUtf8 (), fromLatin1 (),和 fromLocal8Bit ().

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

這是重載函數。

返迴 QString initialized with the UTF-8 string str .

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

該函數在 Qt 6.0 引入。

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

這是重載函數。

返迴 QString initialized with the UTF-8 string str .

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

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

這是重載函數。

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

該函數在 Qt 6.1 引入。

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

這是重載函數。

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

該函數在 Qt 6.0 引入。

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

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

size is -1 (default), unicode must be '\0'-terminated.

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

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

QString makes a deep copy of the Unicode data.

另請參閱 utf16 (), setUtf16 (),和 fromStdU16String ().

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

Reads the first size code units of the wchar_t array to whose start string points, converting them to Unicode and returning the result as a QString . The encoding used by wchar_t is assumed to be UTF-32 if the type's size is four bytes or UTF-16 if its size is two bytes.

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

另請參閱 fromUtf16 (), fromLatin1 (), fromLocal8Bit (), fromUtf8 (), fromUcs4 (),和 fromStdWString ().

QChar &QString:: front ()

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

此函數為兼容 STL (標準模闆庫) 提供。

警告: 在空字符串調用此函數,將構成未定義行為。

另請參閱 back (), at (),和 operator[] ().

QChar QString:: front () const

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

此函數為兼容 STL (標準模闆庫) 提供。

警告: 在空字符串調用此函數,將構成未定義行為。

另請參閱 back (), at (),和 operator[] ().

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

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

cs is Qt::CaseSensitive (默認),搜索區分大小寫;否則,搜索不區分大小寫。

範例:

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

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

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

若匹配成功且 rmatch 不是 nullptr ,它還把匹配結果寫入 QRegularExpressionMatch 對象指嚮的 rmatch .

範例:

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

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

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

cs is Qt::CaseSensitive (默認),搜索區分大小寫;否則,搜索不區分大小寫。

範例:

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

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

此函數重載 indexOf()。

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

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

此函數重載 indexOf()。

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

cs is Qt::CaseSensitive (默認),搜索區分大小寫;否則,搜索不區分大小寫。

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

另請參閱 QStringView::indexOf (), lastIndexOf (), contains (),和 count ().

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

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

範例:

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

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

另請參閱 append (), prepend (), replace (),和 remove ().

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

This function overloads insert().

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

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

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

This function overloads insert().

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

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

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

This function overloads insert().

Inserts the string view str at the given index position 並返迴此字符串的引用。

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

該函數在 Qt 6.0 引入。

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

This function overloads insert().

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

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

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

該函數在 Qt 6.5 引入。

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

This function overloads insert().

Interprets the contents of str as UTF-8, inserts the Unicode string it encodes at the given index position 並返迴此字符串的引用。

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

This function is not available when QT_NO_CAST_FROM_ASCII 有定義。

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

This function overloads insert().

Inserts the C string str at the given index position 並返迴此字符串的引用。

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

This function is not available when QT_NO_CAST_FROM_ASCII 有定義。

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

This function overloads insert().

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

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

[noexcept] bool QString:: isEmpty () const

返迴 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:: isLower () const

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

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

另請參閱 QChar::toLower () 和 isUpper ().

bool QString:: isNull () const

返迴 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

返迴 true if the string is read right to left.

另請參閱 QStringView::isRightToLeft ().

bool QString:: isUpper () const

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

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

另請參閱 QChar::toUpper () 和 isLower ().

[noexcept] bool QString:: isValidUtf16 () const

返迴 true if the string contains valid UTF-16 encoded data, or false 否則。

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

另請參閱 QStringView::isValidUtf16 ().

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

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

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

返迴 -1,若 re didn't match anywhere.

若匹配成功且 rmatch 不是 nullptr ,它還把匹配結果寫入 QRegularExpressionMatch 對象指嚮的 rmatch .

範例:

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

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

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

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

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

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

返迴 -1,若 str 找不到。

cs is Qt::CaseSensitive (默認),搜索區分大小寫;否則,搜索不區分大小寫。

範例:

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
					

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

另請參閱 indexOf (), contains (),和 count ().

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

This function overloads lastIndexOf().

該函數在 Qt 6.3 引入。

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

This function overloads lastIndexOf().

Returns the index position of the last occurrence of the string str in this string. Returns -1 if str 找不到。

cs is Qt::CaseSensitive (默認),搜索區分大小寫;否則,搜索不區分大小寫。

範例:

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 6.2 引入。

另請參閱 indexOf (), contains (),和 count ().

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

This function overloads lastIndexOf().

Returns the index position of the last occurrence of the string view str in this string. Returns -1 if str 找不到。

cs is Qt::CaseSensitive (默認),搜索區分大小寫;否則,搜索不區分大小寫。

該函數在 Qt 6.2 引入。

另請參閱 indexOf (), contains (),和 count ().

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

This function overloads lastIndexOf().

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

若匹配成功且 rmatch 不是 nullptr ,它還把匹配結果寫入 QRegularExpressionMatch 對象指嚮的 rmatch .

範例:

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

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

該函數在 Qt 6.2 引入。

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

This function overloads lastIndexOf().

Returns the index position of the last occurrence of the string str in this string. Returns -1 if str 找不到。

cs is Qt::CaseSensitive (默認),搜索區分大小寫;否則,搜索不區分大小寫。

範例:

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 6.2 引入。

另請參閱 indexOf (), contains (),和 count ().

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

This function overloads lastIndexOf().

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

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

This function overloads lastIndexOf().

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

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

返迴 -1,若 str 找不到。

cs is Qt::CaseSensitive (默認),搜索區分大小寫;否則,搜索不區分大小寫。

範例:

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
					

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

另請參閱 indexOf (), contains (),和 count ().

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

This function overloads lastIndexOf().

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

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

返迴 -1,若 str 找不到。

cs is Qt::CaseSensitive (默認),搜索區分大小寫;否則,搜索不區分大小寫。

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

另請參閱 indexOf (), contains (),和 count ().

QString QString:: leftJustified ( qsizetype width , QChar fill = u' ', bool truncate = false) const

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

truncate is false 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 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 ().

[noexcept] qsizetype QString:: length () const

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

另請參閱 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.

另請參閱 compare (), QLocale ,和 Comparing Strings .

[since 6.0] int QString:: localeAwareCompare ( QStringView other ) const

This function overloads localeAwareCompare().

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

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 6.0 引入。

另請參閱 Comparing Strings .

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

This function overloads localeAwareCompare().

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

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

另請參閱 Comparing Strings .

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

This function overloads 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 6.0 引入。

另請參閱 Comparing Strings .

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

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

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

Returns a string equivalent of the number n 根據指定 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.

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

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

另請參閱 setNum ().

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

Returns a string representing the floating-point number n .

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

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

另請參閱 setNum (), QLocale::toString (), QLocale::FloatingPointPrecisionOption ,和 Number Formats .

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

這是重載函數。

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

這是重載函數。

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

這是重載函數。

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

這是重載函數。

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

這是重載函數。

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

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

This operation is typically very fast ( 常量時間 ),因為 QString preallocates extra space at the beginning of the string data, so it can grow without reallocating the entire string each time.

範例:

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

另請參閱 append () 和 insert ().

QString &QString:: prepend ( QChar ch )

This function overloads prepend().

前置字符 ch 到此字符串。

QString &QString:: prepend ( QLatin1StringView str )

This function overloads prepend().

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

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

This function overloads prepend().

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

該函數在 Qt 6.0 引入。

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

This function overloads prepend().

Prepends the UTF-8 string view str 到此字符串。

該函數在 Qt 6.5 引入。

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

This function overloads prepend().

前置字節數組 ba to this string. The byte array is converted to Unicode using the fromUtf8 () 函數。

可以禁用此函數通過定義 QT_NO_CAST_FROM_ASCII when you compile your applications. This can be useful if you want to ensure that all user-visible strings go through QObject::tr (), for example.

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

This function overloads prepend().

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

可以禁用此函數通過定義 QT_NO_CAST_FROM_ASCII when you compile your applications. This can be useful if you want to ensure that all user-visible strings go through QObject::tr (), for example.

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

This function overloads prepend().

前置 len 字符來自 QChar array str to this string and returns a reference to this string.

void QString:: push_back (const QString & other )

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

另請參閱 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::reverse_iterator QString:: rbegin ()

返迴 STL-style reverse iterator pointing to the first character in the string, in reverse order.

警告: 返迴迭代器不驗證當分離時或當 QString 被修改。

另請參閱 begin (), crbegin (),和 rend ().

QString::const_reverse_iterator QString:: rbegin () const

這是重載函數。

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

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

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

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

另請參閱 indexOf (), lastIndexOf (),和 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 (默認),搜索區分大小寫;否則,搜索不區分大小寫。

範例:

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

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

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

另請參閱 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 (默認),搜索區分大小寫;否則,搜索不區分大小寫。

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

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

另請參閱 replace ().

QString &QString:: remove ( qsizetype position , qsizetype 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 .

n is <= 0 nothing is changed.

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

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

另請參閱 insert () 和 replace ().

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

這是重載函數。

Removes every occurrence of the given Latin-1 string viewed by str from this string, and returns a reference to this string.

cs is Qt::CaseSensitive (默認),搜索區分大小寫;否則,搜索不區分大小寫。

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

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

另請參閱 replace ().

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

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

該函數在 Qt 6.5 引入。

另請參閱 remove ().

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

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

該函數在 Qt 6.5 引入。

另請參閱 remove ().

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

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

該函數在 Qt 6.1 引入。

另請參閱 remove ().

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

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

該函數在 Qt 6.5 引入。

另請參閱 remove ().

QString::reverse_iterator QString:: rend ()

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

警告: 返迴迭代器不驗證當分離時或當 QString 被修改。

另請參閱 end (), crend (),和 rbegin ().

QString::const_reverse_iterator QString:: rend () const

這是重載函數。

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

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

替換 n characters beginning at index position 采用字符串 after 並返迴此字符串的引用。

注意: 若指定 position index is within the string, but position + n goes outside the strings range, then n will be adjusted to stop at the end of the string.

範例:

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

另請參閱 insert () 和 remove ().

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

此函數重載 replace()。

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

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

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

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

另請參閱 indexOf (), lastIndexOf (), remove (), QRegularExpression ,和 QRegularExpressionMatch .

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 (默認),搜索區分大小寫;否則,搜索不區分大小寫。

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

此函數重載 replace()。

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

cs is Qt::CaseSensitive (默認),搜索區分大小寫;否則,搜索不區分大小寫。

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

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 (默認),搜索區分大小寫;否則,搜索不區分大小寫。

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

此函數重載 replace()。

Replaces every occurrence in this string of the Latin-1 string viewed by before with the Latin-1 string viewed by after , and returns a reference to this string.

cs is Qt::CaseSensitive (默認),搜索區分大小寫;否則,搜索不區分大小寫。

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

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

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

此函數重載 replace()。

Replaces every occurrence in this string of the Latin-1 string viewed by before 采用字符串 after , and returns a reference to this string.

cs is Qt::CaseSensitive (默認),搜索區分大小寫;否則,搜索不區分大小寫。

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

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

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

此函數重載 replace()。

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

cs is Qt::CaseSensitive (默認),搜索區分大小寫;否則,搜索不區分大小寫。

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

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

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

此函數重載 replace()。

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

cs is Qt::CaseSensitive (默認),搜索區分大小寫;否則,搜索不區分大小寫。

範例:

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"
					

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

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

此函數重載 replace()。

替換 n characters beginning at index position with the character after 並返迴此字符串的引用。

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

此函數重載 replace()。

替換 n characters beginning at index position with the first alen characters of the QChar array after 並返迴此字符串的引用。

QString &QString:: replace (const QChar * before , qsizetype blen , const QChar * after , qsizetype 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 (默認),搜索區分大小寫;否則,搜索不區分大小寫。

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

void QString:: reserve ( qsizetype size )

Ensures the string has space for at least size 字符。

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

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

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

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

QString result;
qsizetype maxSize;
bool condition;
QChar nextChar;
result.reserve(maxSize);
while (condition)
    result.append(nextChar);
result.squeeze();
					

另請參閱 squeeze (), capacity (),和 resize ().

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

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

範例:

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

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

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

size 為負,相當於傳遞 0。

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

另請參閱 truncate (), reserve (),和 squeeze ().

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

這是重載函數。

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

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

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

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

The behavior is identical to resize(size) .

該函數在 Qt 6.8 引入。

另請參閱 resize ().

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

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

This function returns a section of the string.

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

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

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

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 QRegularExpression & re , qsizetype start , qsizetype end = -1, QString::SectionFlags flags = SectionDefault) const

This function overloads section().

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

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

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

另請參閱 split () 和 simplified ().

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

This function overloads section().

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

另請參閱 split ().

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.

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.

另請參閱 number ().

QString &QString:: setNum ( long 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 ( uint n , int base = 10)

這是重載函數。

QString &QString:: setNum ( ulong 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.

另請參閱 number (), QLocale::FloatingPointPrecisionOption ,和 Number Formats .

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.

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

另請參閱 number ().

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

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

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

另請參閱 fromRawData ().

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

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

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

另請參閱 unicode () 和 setUtf16 ().

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

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

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

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

另請參閱 utf16 () 和 setUnicode ().

void QString:: shrink_to_fit ()

此函數為兼容 STL (標準模闆庫) 提供。它相當於 squeeze ().

另請參閱 squeeze ().

QString QString:: simplified () const

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

空白意味著任何字符其。 QChar::isSpace () 返迴 true 。這包括 ASCII 字符 \t、\n、\v、\f、\r、及 " "。

範例:

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

另請參閱 trimmed ().

[noexcept] qsizetype QString:: size () const

Returns the number of characters in this string.

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

範例:

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

另請參閱 isEmpty () 和 resize ().

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

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

注意: 行為未定義若 pos < 0, n < 0, or pos + n > size ().

QString x = u"Nine pineapples"_s;
x.slice(5);     // x == "pineapples"
x.slice(4, 3);  // x == "app"
					

該函數在 Qt 6.8 引入。

另請參閱 sliced (), first (), last (), chopped (), chop (),和 truncate ().

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

這是重載函數。

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

注意: 行為未定義若 pos < 0 or pos > size ().

該函數在 Qt 6.8 引入。

另請參閱 sliced (), first (), last (), chopped (), chop (),和 truncate ().

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

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

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

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

範例:

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

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

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

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

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

另請參閱 QStringList::join () 和 section ().

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

這是重載函數。

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

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

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

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

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

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

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

另請參閱 QStringList::join () 和 section ().

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

這是重載函數。

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

返迴 true if the string starts with s ;否則返迴 false .

cs is Qt::CaseSensitive (默認),搜索區分大小寫;否則,搜索不區分大小寫。

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

另請參閱 endsWith ().

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

This function overloads startsWith().

返迴 true if the string starts with c ;否則返迴 false .

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

This function overloads startsWith().

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

這是重載函數。

返迴 true if the string starts with the string view str ;否則返迴 false .

cs is Qt::CaseSensitive (默認),搜索區分大小寫;否則,搜索不區分大小寫。

另請參閱 endsWith ().

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

Swaps this string with other 。此操作很快且從不失敗。

CFStringRef QString:: toCFString () const

Creates a CFString from a QString .

The caller owns the CFString and is responsible for releasing it.

注意: 此函數隻可用於 macOS 和 iOS。

QString QString:: toCaseFolded () const

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

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

Returns the string converted to a double 值。

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

ok 不是 nullptr , failure is reported by setting * ok to false , and success by setting * ok to true .

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

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

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

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

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

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

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

此函數忽略前導和結尾空格。

另請參閱 number (), QLocale::setDefault (), QLocale::toDouble (),和 trimmed ().

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

Converts this object to an ECMAScript string .

該函數在 Qt 6.6 引入。

另請參閱 fromEcmaString ().

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

Returns the string converted to a float 值。

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

ok 不是 nullptr , failure is reported by setting * ok to false , and success by setting * ok to true .

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

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

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

範例:

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

此函數忽略前導和結尾空格。

另請參閱 number (), toDouble (), toInt (), QLocale::toFloat (),和 trimmed ().

QString QString:: toHtmlEscaped () const

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

範例:

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

int QString:: toInt ( bool * ok = nullptr, 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.

ok 不是 nullptr , failure is reported by setting * ok to false , and success by setting * ok to true .

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

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

範例:

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
					

此函數忽略前導和結尾空格。

注意: 在 Qt 6.4 添加對 0b 前綴的支持。

另請參閱 number (), toUInt (), toDouble (),和 QLocale::toInt ().

QByteArray QString:: toLatin1 () const

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

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

另請參閱 fromLatin1 (), toUtf8 (), toLocal8Bit (),和 QStringEncoder .

QByteArray QString:: toLocal8Bit () const

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

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

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

另請參閱 fromLocal8Bit (), toLatin1 (), toUtf8 (),和 QStringEncoder .

long QString:: toLong ( bool * ok = nullptr, 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.

ok 不是 nullptr , failure is reported by setting * ok to false , and success by setting * ok to true .

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

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

範例:

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
					

此函數忽略前導和結尾空格。

注意: 在 Qt 6.4 添加對 0b 前綴的支持。

另請參閱 number (), toULong (), toInt (),和 QLocale::toInt ().

qlonglong QString:: toLongLong ( bool * ok = nullptr, 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.

ok 不是 nullptr , failure is reported by setting * ok to false , and success by setting * ok to true .

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

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

範例:

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
					

此函數忽略前導和結尾空格。

注意: 在 Qt 6.4 添加對 0b 前綴的支持。

另請參閱 number (), toULongLong (), toInt (),和 QLocale::toLongLong ().

QString QString:: toLower () const

Returns a lowercase copy of the string.

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

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

另請參閱 toUpper () 和 QLocale::toLower ().

NSString *QString:: toNSString () const

Creates a NSString from a QString .

The NSString is autoreleased.

注意: 此函數隻可用於 macOS 和 iOS。

short QString:: toShort ( bool * ok = nullptr, 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.

ok 不是 nullptr , failure is reported by setting * ok to false , and success by setting * ok to true .

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

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

範例:

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
					

此函數忽略前導和結尾空格。

注意: 在 Qt 6.4 添加對 0b 前綴的支持。

另請參閱 number (), toUShort (), toInt (),和 QLocale::toShort ().

std::string QString:: toStdString () const

返迴 std::string 對象帶有的數據包含在此 QString . The Unicode data is converted into 8-bit characters using the toUtf8 () 函數。

This method is mostly useful to pass a QString 到接受 std::string 對象的函數。

另請參閱 toLatin1 (), toUtf8 (), toLocal8Bit (),和 QByteArray::toStdString ().

std::u16string QString:: toStdU16String () const

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

另請參閱 utf16 (), toStdWString (),和 toStdU32String ().

std::u32string QString:: toStdU32String () const

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

另請參閱 toUcs4 (), toStdWString (),和 toStdU16String ().

std::wstring QString:: toStdWString () const

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

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

另請參閱 utf16 (), toLatin1 (), toUtf8 (), toLocal8Bit (), toStdU16String (),和 toStdU32String ().

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

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

ok 不是 nullptr , failure is reported by setting * ok to false , and success by setting * ok to true .

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

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

範例:

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
					

此函數忽略前導和結尾空格。

注意: 在 Qt 6.4 添加對 0b 前綴的支持。

另請參閱 number (), toInt (),和 QLocale::toUInt ().

ulong QString:: toULong ( bool * ok = nullptr, 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.

ok 不是 nullptr , failure is reported by setting * ok to false , and success by setting * ok to true .

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

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

範例:

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
					

此函數忽略前導和結尾空格。

注意: 在 Qt 6.4 添加對 0b 前綴的支持。

另請參閱 number () 和 QLocale::toUInt ().

qulonglong QString:: toULongLong ( bool * ok = nullptr, 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.

ok 不是 nullptr , failure is reported by setting * ok to false , and success by setting * ok to true .

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

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

範例:

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
					

此函數忽略前導和結尾空格。

注意: 在 Qt 6.4 添加對 0b 前綴的支持。

另請參閱 number (), toLongLong (),和 QLocale::toULongLong ().

ushort QString:: toUShort ( bool * ok = nullptr, 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.

ok 不是 nullptr , failure is reported by setting * ok to false , and success by setting * ok to true .

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

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

範例:

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
					

此函數忽略前導和結尾空格。

注意: 在 Qt 6.4 添加對 0b 前綴的支持。

另請參閱 number (), toShort (),和 QLocale::toUShort ().

QList < uint > QString:: toUcs4 () const

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

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

The returned list is not 0-terminated.

另請參閱 fromUtf8 (), toUtf8 (), toLatin1 (), toLocal8Bit (), QStringEncoder , 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 ().

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

另請參閱 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 .

另請參閱 fromUtf8 (), toLatin1 (), toLocal8Bit (),和 QStringEncoder .

qsizetype QString:: toWCharArray ( wchar_t * array ) const

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

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

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

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

另請參閱 utf16 (), toUcs4 (), toLatin1 (), toUtf8 (), toLocal8Bit (), toStdWString (),和 QStringView::toWCharArray ().

QString QString:: trimmed () const

返迴從開始到結束之間,已移除空白的字符串。

空白意味著任何字符其。 QChar::isSpace () 返迴 true 。這包括 ASCII 字符 \t、\n、\v、\f、\r、及 " "。

範例:

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

不像 simplified (),trimmed() 隻留下內部空白。

另請參閱 simplified ().

void QString:: truncate ( qsizetype position )

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

若指定 position 索引超齣字符串末尾,什麼都不發生。

範例:

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

position 為負,相當於傳遞 0。

另請參閱 chop (), resize (), first (),和 QStringView::truncate ().

const QChar *QString:: unicode () const

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

注意: 返迴字符串不能以 \0 結尾。使用 size () 以確定數組的長度。

另請參閱 setUnicode (), utf16 (),和 fromRawData ().

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

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

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

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

另請參閱 asprintf ().

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

轉換此 QString object to a std::u16string_view 對象。

該函數在 Qt 6.7 引入。

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

This function overloads operator+=().

追加字符 ch to the string.

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

This function overloads operator+=().

追加 Latin-1 字符串視圖通過 str 到此字符串。

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

This function overloads operator+=().

Appends the string view str 到此字符串。

該函數在 Qt 6.0 引入。

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

This function overloads operator+=().

追加 UTF-8 字符串視圖 str 到此字符串。

該函數在 Qt 6.5 引入。

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

This function overloads operator+=().

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

可以禁用此函數通過定義 QT_NO_CAST_FROM_ASCII when you compile your applications. This can be useful if you want to ensure that all user-visible strings go through QObject::tr (), for example.

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

This function overloads operator+=().

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

可以禁用此函數通過定義 QT_NO_CAST_FROM_ASCII when you compile your applications. This can be useful if you want to ensure that all user-visible strings go through QObject::tr (), for example.

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

移動賦值 other 到此 QString 實例。

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

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

QString &QString:: operator= ( QChar ch )

此函數重載 operator=()。

Sets the string to contain the single character ch .

QString &QString:: operator= ( QLatin1StringView str )

此函數重載 operator=()。

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

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

此函數重載 operator=()。

賦值 ba to this string. The byte array is converted to Unicode using the fromUtf8 () 函數。

可以禁用此運算符通過定義 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 fromUtf8 () 函數。

可以禁用此運算符通過定義 QT_NO_CAST_FROM_ASCII or QT_RESTRICTED_CAST_FROM_ASCII when you compile your applications. This can be useful if you want to ensure that all user-visible strings go through QObject::tr (), for example.

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

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

範例:

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

另請參閱 at ().

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

This function overloads operator[]().

相關非成員

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

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

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

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

Removes all elements that compare equal to t 從字符串 s . Returns the number of elements removed, if any.

該函數在 Qt 6.1 引入。

另請參閱 erase_if .

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

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

該函數在 Qt 6.1 引入。

另請參閱 erase .

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

返迴 true 若字節數組 lhs is not equal to the UTF-8 encoding of rhs ;否則返迴 false .

比較是區分大小寫的。

可以禁用此運算符通過定義 QT_NO_CAST_FROM_ASCII 當編譯應用程序時。那麼需要調用 QString::fromUtf8 (), QString::fromLatin1 (),或 QString::fromLocal8Bit () explicitly if you want to convert the byte array to a QString before doing the comparison.

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

返迴 true 若字符串 lhs 不等於字符串 rhs ;否則返迴 false .

另請參閱 Comparing Strings .

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

返迴 true if lhs 不等於 rhs ;否則返迴 false .

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

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

This function overloads operator!=().

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

可以禁用此運算符通過定義 QT_NO_CAST_FROM_ASCII when you compile your applications. This can be useful if you want to ensure that all user-visible strings go through QObject::tr (), for example.

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

返迴 true 若字符串 lhs 不等於字符串 rhs . Otherwise returns false .

This function overloads operator!=().

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

This function overloads operator!=().

The rhs const char pointer is converted to a QUtf8StringView .

可以禁用此運算符通過定義 QT_NO_CAST_FROM_ASCII when you compile your applications. This can be useful if you want to ensure that all user-visible strings go through QObject::tr (), for example.

[noexcept, since 6.4] QString operator""_s (const char16_t * str , size_t size )

文字運算符創建的 QString out of the first size characters in the char16_t string literal str .

The QString is created at compile time, and the generated string data is stored in the read-only segment of the compiled object file. Duplicate literals may share the same read-only memory. This functionality is interchangeable with QStringLiteral , but saves typing when many string literals are present in the code.

以下代碼創建 QString :

using namespace Qt::Literals::StringLiterals;
auto str = u"hello"_s;
					

該函數在 Qt 6.4 引入。

另請參閱 Qt::Literals::StringLiterals .

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

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

另請參閱 QString::fromUtf8 ().

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

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

另請參閱 QString::fromUtf8 ().

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

返迴 true 若字節數組 lhs is lexically less than the UTF-8 encoding of rhs ;否則返迴 false .

比較是區分大小寫的。

可以禁用此運算符通過定義 QT_NO_CAST_FROM_ASCII 當編譯應用程序時。那麼需要調用 QString::fromUtf8 (), QString::fromLatin1 (),或 QString::fromLocal8Bit () explicitly if you want to convert the byte array to a QString before doing the comparison.

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

返迴 true if lhs is lexically less than rhs ;否則返迴 false 。對於 lhs != 0, this is equivalent to compare(lhs, rhs) < 0 .

另請參閱 Comparing Strings .

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

This function overloads operator<().

返迴 true if lhs is lexically less than rhs ;否則返迴 false .

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

This function overloads operator<().

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

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

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

This function overloads operator<().

返迴 true if lhs is lexically less than rhs ;否則返迴 false .

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

This function overloads operator<().

返迴 true 若字符串 lhs 詞法上小於字符串 rhs ;否則返迴 false .

另請參閱 Comparing Strings .

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

返迴 true 若字符串 lhs 詞法上小於字符串 rhs . Otherwise returns false .

This function overloads operator<().

The rhs const char pointer is converted to a QUtf8StringView .

可以禁用此運算符通過定義 QT_NO_CAST_FROM_ASCII when you compile your applications. This can be useful if you want to ensure that all user-visible strings go through QObject::tr (), for example.

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

寫入給定 string 到指定 stream .

另請參閱 序列化 Qt 數據類型 .

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

返迴 true 若字節數組 lhs is lexically less than or equal to the UTF-8 encoding of rhs ;否則返迴 false .

比較是區分大小寫的。

可以禁用此運算符通過定義 QT_NO_CAST_FROM_ASCII 當編譯應用程序時。那麼需要調用 QString::fromUtf8 (), QString::fromLatin1 (),或 QString::fromLocal8Bit () explicitly if you want to convert the byte array to a QString before doing the comparison.

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

返迴 true 若字符串 lhs 詞法上 <= 字符串 rhs ;否則返迴 false .

另請參閱 Comparing Strings .

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

返迴 true if lhs is lexically less than or equal to rhs ;否則返迴 false 。對於 lhs != 0, this is equivalent to compare(lhs, rhs) <= 0 .

另請參閱 Comparing Strings .

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

This function overloads operator<=().

返迴 true if lhs is lexically less than or equal to rhs ;否則返迴 false .

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

This function overloads operator<=().

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

可以禁用此運算符通過定義 QT_NO_CAST_FROM_ASCII when you compile your applications. This can be useful if you want to ensure that all user-visible strings go through QObject::tr (), for example.

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

This function overloads operator<=().

返迴 true if lhs is lexically less than or equal to rhs ;否則返迴 false .

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

This function overloads operator<=().

The rhs const char pointer is converted to a QUtf8StringView .

可以禁用此運算符通過定義 QT_NO_CAST_FROM_ASCII when you compile your applications. This can be useful if you want to ensure that all user-visible strings go through QObject::tr (), for example.

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

返迴 true 若字節數組 lhs is equal to the UTF-8 encoding of rhs ;否則返迴 false .

比較是區分大小寫的。

可以禁用此運算符通過定義 QT_NO_CAST_FROM_ASCII 當編譯應用程序時。那麼需要調用 QString::fromUtf8 (), QString::fromLatin1 (),或 QString::fromLocal8Bit () explicitly if you want to convert the byte array to a QString before doing the comparison.

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

This function overloads operator==().

返迴 true if lhs 等於 rhs ;否則返迴 false .

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

This function overloads operator==().

The rhs byte array is converted to a QUtf8StringView .

可以禁用此運算符通過定義 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.

返迴 true 若字符串 lhs is lexically equal to rhs . Otherwise returns false .

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

This function overloads operator==().

返迴 true if lhs 等於 rhs ;否則返迴 false .

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

This function overloads operator==().

返迴 true 若字符串 lhs 等於字符串 rhs ;否則返迴 false .

注意: This function treats null strings the same as empty strings, for more details see null 和空字符串之間的區彆 .

另請參閱 Comparing Strings .

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

This function overloads operator==().

The rhs const char pointer is converted to a QUtf8StringView .

可以禁用此運算符通過定義 QT_NO_CAST_FROM_ASCII when you compile your applications. This can be useful if you want to ensure that all user-visible strings go through QObject::tr (), for example.

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

This function overloads operator==().

返迴 true if lhs 等於 rhs ;否則返迴 false . Note that no string is equal to lhs being 0.

相當於 lhs != 0 && compare(lhs, rhs) == 0 .

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

返迴 true 若字節數組 lhs is lexically greater than the UTF-8 encoding of rhs ;否則返迴 false .

比較是區分大小寫的。

可以禁用此運算符通過定義 QT_NO_CAST_FROM_ASCII 當編譯應用程序時。那麼需要調用 QString::fromUtf8 (), QString::fromLatin1 (),或 QString::fromLocal8Bit () explicitly if you want to convert the byte array to a QString before doing the comparison.

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

返迴 true 若字符串 lhs 詞法上大於字符串 rhs ;否則返迴 false .

另請參閱 Comparing Strings .

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

返迴 true if lhs is lexically greater than rhs ;否則返迴 false . Equivalent to compare(lhs, rhs) > 0 .

另請參閱 Comparing Strings .

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

This function overloads operator>().

返迴 true if lhs is lexically greater than rhs ;否則返迴 false .

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

This function overloads operator>().

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

可以禁用此運算符通過定義 QT_NO_CAST_FROM_ASCII when you compile your applications. This can be useful if you want to ensure that all user-visible strings go through QObject::tr (), for example.

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

This function overloads operator>().

返迴 true if lhs is lexically greater than rhs ;否則返迴 false .

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

This function overloads operator>().

The rhs const char pointer is converted to a QUtf8StringView .

可以禁用此運算符通過定義 QT_NO_CAST_FROM_ASCII when you compile your applications. This can be useful if you want to ensure that all user-visible strings go through QObject::tr (), for example.

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

返迴 true 若字節數組 lhs is greater than or equal to the UTF-8 encoding of rhs ;否則返迴 false .

比較是區分大小寫的。

可以禁用此運算符通過定義 QT_NO_CAST_FROM_ASCII 當編譯應用程序時。那麼需要調用 QString::fromUtf8 (), QString::fromLatin1 (),或 QString::fromLocal8Bit () explicitly if you want to convert the byte array to a QString before doing the comparison.

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

返迴 true 若字符串 lhs 詞法上大於等於字符串 rhs ;否則返迴 false .

另請參閱 Comparing Strings .

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

返迴 true if lhs is lexically greater than or equal to rhs ;否則返迴 false 。對於 lhs != 0, this is equivalent to compare(lhs, rhs) >= 0 .

另請參閱 Comparing Strings .

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

此函數重載運算符 >=()。

返迴 true if lhs is lexically greater than or equal to rhs ;否則返迴 false .

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

此函數重載運算符 >=()。

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

可以禁用此運算符通過定義 QT_NO_CAST_FROM_ASCII when you compile your applications. This can be useful if you want to ensure that all user-visible strings go through QObject::tr (), for example.

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

此函數重載運算符 >=()。

返迴 true if lhs is lexically greater than or equal to rhs ;否則返迴 false .

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

此函數重載運算符 >=()。

The rhs const char pointer is converted to a QUtf8StringView .

可以禁用此運算符通過定義 QT_NO_CAST_FROM_ASCII when you compile your applications. This can be useful if you want to ensure that all user-visible strings go through QObject::tr (), for example.

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

讀取字符串從指定 stream 進給定 string .

另請參閱 序列化 Qt 數據類型 .

宏文檔編製

QStringLiteral ( str )

宏生成數據為 QString 從字符串文字 str 在編譯時。創建 QString from it is free in this case, and the generated string data is stored in the read-only segment of the compiled object file.

If you have code that looks like this:

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

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

This cost can be avoided by using QStringLiteral instead:

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

在此情況下, QString 's internal data will be generated at compile time; no conversion or allocation will occur at runtime.

Using QStringLiteral instead of a double quoted plain C++ string literal can significantly speed up creation of QString 實例從編譯時的已知數據。

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

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

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

另請參閱 QByteArrayLiteral .

QT_NO_CAST_FROM_ASCII

禁用自動轉換從 8 位字符串 ( char * ) to Unicode QStrings, as well as from 8-bit char 類型 ( char and unsigned char ) 到 QChar .

另請參閱 QT_NO_CAST_TO_ASCII , QT_RESTRICTED_CAST_FROM_ASCII ,和 QT_NO_CAST_FROM_BYTEARRAY .

QT_NO_CAST_TO_ASCII

禁用自動轉換從 QString 到 8 位字符串 ( char * ).

另請參閱 QT_NO_CAST_FROM_ASCII , QT_RESTRICTED_CAST_FROM_ASCII ,和 QT_NO_CAST_FROM_BYTEARRAY .

QT_RESTRICTED_CAST_FROM_ASCII

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

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

另請參閱 QT_NO_CAST_FROM_ASCII and QT_NO_CAST_TO_ASCII .

const char * qPrintable (const QString & str )

返迴 str 作為 const char * 。這相當於 str . toLocal8Bit (). constData ().

The char pointer will be invalid after the statement in which qPrintable() is used. This is because the array returned by QString::toLocal8Bit () will fall out of scope.

注意: qDebug (), qInfo (), qWarning (), qCritical (), qFatal () expect %s arguments to be UTF-8 encoded, while qPrintable() converts to local 8-bit encoding. Therefore qUtf8Printable () should be used for logging strings instead of qPrintable().

另請參閱 qUtf8Printable ().

const wchar_t * qUtf16Printable (const QString & str )

返迴 str 作為 const ushort * ,但鑄造成 const wchar_t * 以避免警告。這相當於 str . utf16 () plus some casting.

The only useful thing you can do with the return value of this macro is to pass it to QString::asprintf () for use in a %ls conversion. In particular, the return value is not 有效 const wchar_t* !

In general, the pointer will be invalid after the statement in which qUtf16Printable() is used. This is because the pointer may have been obtained from a temporary expression, which will fall out of scope.

範例:

qWarning("%ls: %ls", qUtf16Printable(key), qUtf16Printable(value));
					

另請參閱 qPrintable (), qDebug (), qInfo (), qWarning (), qCritical (),和 qFatal ().

const char * qUtf8Printable (const QString & str )

返迴 str 作為 const char * 。這相當於 str . toUtf8 (). constData ().

The char pointer will be invalid after the statement in which qUtf8Printable() is used. This is because the array returned by QString::toUtf8 () will fall out of scope.

範例:

qWarning("%s: %s", qUtf8Printable(key), qUtf8Printable(value));
					

另請參閱 qPrintable (), qDebug (), qInfo (), qWarning (), qCritical (),和 qFatal ().