QString 类提供 Unicode 字符串。 更多...
头: | #include <QString> |
CMake: |
find_package(Qt6 COMPONENTS Core REQUIRED)
target_link_libraries(mytarget PRIVATE Qt6::Core) |
qmake: | QT += core |
注意: 此类的所有函数 可重入 .
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 (const QByteArray & ba ) | |
QString (const char * str ) | |
QString (QString && other ) | |
QString (const QString & other ) | |
QString (const char8_t * str ) | |
QString (QLatin1String str ) | |
QString (qsizetype size , QChar ch ) | |
QString (QChar ch ) | |
QString (const QChar * unicode , qsizetype size = -1) | |
QString () | |
QString & | operator= (const QByteArray & ba ) |
QString & | operator= (QString && other ) |
QString & | operator= (const QString & other ) |
~QString () | |
QString & | append (const QString & str ) |
QString & | append (QChar ch ) |
QString & | append (const QChar * str , qsizetype len ) |
QString & | append (QLatin1String str ) |
QString & | append (const char * str ) |
QString & | append (const QByteArray & ba ) |
QString | arg (const QString & a , int fieldWidth = 0, QChar fillChar = QLatin1Char(' ')) const |
QString | arg (qlonglong a , int fieldWidth = 0, int base = 10, QChar fillChar = QLatin1Char(' ')) const |
QString | arg (qulonglong a , int fieldWidth = 0, int base = 10, QChar fillChar = QLatin1Char(' ')) const |
QString | arg (long a , int fieldWidth = 0, int base = 10, QChar fillChar = QLatin1Char(' ')) const |
QString | arg (ulong a , int fieldWidth = 0, int base = 10, QChar fillChar = QLatin1Char(' ')) const |
QString | arg (int a , int fieldWidth = 0, int base = 10, QChar fillChar = QLatin1Char(' ')) const |
QString | arg (uint a , int fieldWidth = 0, int base = 10, QChar fillChar = QLatin1Char(' ')) const |
QString | arg (short a , int fieldWidth = 0, int base = 10, QChar fillChar = QLatin1Char(' ')) const |
QString | arg (ushort a , int fieldWidth = 0, int base = 10, QChar fillChar = QLatin1Char(' ')) const |
QString | arg (double a , int fieldWidth = 0, char format = 'g', int precision = -1, QChar fillChar = QLatin1Char(' ')) const |
QString | arg (char a , int fieldWidth = 0, QChar fillChar = QLatin1Char(' ')) const |
QString | arg (QChar a , int fieldWidth = 0, QChar fillChar = QLatin1Char(' ')) const |
QString | arg (QStringView a , int fieldWidth = 0, QChar fillChar = QLatin1Char(' ')) const |
QString | arg (QLatin1String a , int fieldWidth = 0, QChar fillChar = QLatin1Char(' ')) const |
QString | arg (Args &&... args ) const |
const QChar | at (qsizetype position ) const |
QChar | back () const |
QChar & | back () |
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 ) const |
void | clear () |
int | compare (const QString & other , Qt::CaseSensitivity cs = Qt::CaseSensitive) const |
int | compare (QLatin1String other , Qt::CaseSensitivity cs = Qt::CaseSensitive) const |
int | compare (QStringView s , Qt::CaseSensitivity cs = Qt::CaseSensitive) const |
int | compare (QChar ch , Qt::CaseSensitivity cs = Qt::CaseSensitive) const |
QString::const_iterator | constBegin () const |
const QChar * | constData () const |
QString::const_iterator | constEnd () const |
bool | contains (const QString & str , Qt::CaseSensitivity cs = Qt::CaseSensitive) const |
bool | contains (QChar ch , Qt::CaseSensitivity cs = Qt::CaseSensitive) const |
bool | contains (QLatin1String str , Qt::CaseSensitivity cs = Qt::CaseSensitive) const |
bool | contains (QStringView str , Qt::CaseSensitivity cs = Qt::CaseSensitive) const |
bool | contains (const QRegularExpression & re , QRegularExpressionMatch * rmatch = nullptr) const |
qsizetype | count (const QString & str , Qt::CaseSensitivity cs = Qt::CaseSensitive) const |
qsizetype | count () const |
qsizetype | count (QChar ch , Qt::CaseSensitivity cs = Qt::CaseSensitive) const |
qsizetype | count (QStringView str , Qt::CaseSensitivity cs = Qt::CaseSensitive) const |
qsizetype | count (const QRegularExpression & re ) 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 (QStringView str , Qt::CaseSensitivity cs = Qt::CaseSensitive) const |
bool | endsWith (QLatin1String s , Qt::CaseSensitivity cs = Qt::CaseSensitive) const |
bool | endsWith (QChar c , Qt::CaseSensitivity cs = Qt::CaseSensitive) const |
QString::iterator | erase (QString::const_iterator first , QString::const_iterator last ) |
QString & | fill (QChar ch , qsizetype size = -1) |
QString | first (qsizetype n ) const |
QChar | front () const |
QChar & | front () |
qsizetype | indexOf (QLatin1String 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 (const QString & str , qsizetype from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive) const |
qsizetype | indexOf (QStringView str , qsizetype from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive) const |
qsizetype | indexOf (const QRegularExpression & re , qsizetype from = 0, QRegularExpressionMatch * rmatch = nullptr) const |
QString & | insert (qsizetype position , const QString & str ) |
QString & | insert (qsizetype position , QChar ch ) |
QString & | insert (qsizetype position , const QChar * unicode , qsizetype size ) |
QString & | insert (qsizetype position , QStringView str ) |
QString & | insert (qsizetype position , QLatin1String str ) |
QString & | insert (qsizetype position , const char * str ) |
QString & | insert (qsizetype position , const QByteArray & str ) |
bool | isEmpty () const |
bool | isLower () const |
bool | isNull () const |
bool | isRightToLeft () const |
bool | isUpper () const |
bool | isValidUtf16 () const |
QString | last (qsizetype n ) const |
qsizetype | lastIndexOf (const QString & str , qsizetype from , Qt::CaseSensitivity cs = Qt::CaseSensitive) const |
qsizetype | lastIndexOf (QChar ch , qsizetype from = -1, Qt::CaseSensitivity cs = Qt::CaseSensitive) const |
qsizetype | lastIndexOf (QLatin1String str , Qt::CaseSensitivity cs = Qt::CaseSensitive) const |
qsizetype | lastIndexOf (QLatin1String str , qsizetype from , Qt::CaseSensitivity cs = Qt::CaseSensitive) const |
qsizetype | lastIndexOf (const QString & str , Qt::CaseSensitivity cs = Qt::CaseSensitive) const |
qsizetype | lastIndexOf (QStringView str , Qt::CaseSensitivity cs = Qt::CaseSensitive) const |
qsizetype | lastIndexOf (QStringView str , qsizetype from , Qt::CaseSensitivity cs = Qt::CaseSensitive) const |
qsizetype | lastIndexOf (const QRegularExpression & re , QRegularExpressionMatch * rmatch = nullptr) const |
qsizetype | lastIndexOf (const QRegularExpression & re , qsizetype from , QRegularExpressionMatch * rmatch = nullptr) const |
QString | left (qsizetype n ) const |
QString | leftJustified (qsizetype width , QChar fill = QLatin1Char(' '), bool truncate = false) const |
qsizetype | length () const |
int | localeAwareCompare (const QString & other ) const |
int | localeAwareCompare (QStringView other ) const |
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 (const QChar * str , qsizetype len ) |
QString & | prepend (QStringView str ) |
QString & | prepend (QLatin1String str ) |
QString & | prepend (const char * str ) |
QString & | prepend (const QByteArray & ba ) |
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 (qsizetype position , qsizetype n ) |
QString & | remove (QChar ch , Qt::CaseSensitivity cs = Qt::CaseSensitive) |
QString & | remove (QLatin1String str , Qt::CaseSensitivity cs = Qt::CaseSensitive) |
QString & | remove (const QString & str , Qt::CaseSensitivity cs = Qt::CaseSensitive) |
QString & | remove (const QRegularExpression & re ) |
QString & | removeIf (Predicate pred ) |
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 (qsizetype position , qsizetype n , QChar after ) |
QString & | replace (qsizetype position , qsizetype n , const QChar * unicode , qsizetype size ) |
QString & | replace (QChar before , QChar after , Qt::CaseSensitivity cs = Qt::CaseSensitive) |
QString & | replace (const QChar * before , qsizetype blen , const QChar * after , qsizetype alen , Qt::CaseSensitivity cs = Qt::CaseSensitive) |
QString & | replace (QLatin1String before , QLatin1String after , Qt::CaseSensitivity cs = Qt::CaseSensitive) |
QString & | replace (QLatin1String before , const QString & after , Qt::CaseSensitivity cs = Qt::CaseSensitive) |
QString & | replace (const QString & before , QLatin1String after , Qt::CaseSensitivity cs = Qt::CaseSensitive) |
QString & | replace (const QString & before , const QString & after , Qt::CaseSensitivity cs = Qt::CaseSensitive) |
QString & | replace (QChar ch , const QString & after , Qt::CaseSensitivity cs = Qt::CaseSensitive) |
QString & | replace (QChar c , QLatin1String after , Qt::CaseSensitivity cs = Qt::CaseSensitive) |
QString & | replace (const QRegularExpression & re , const QString & after ) |
void | reserve (qsizetype size ) |
void | resize (qsizetype size ) |
void | resize (qsizetype size , QChar fillChar ) |
QString | right (qsizetype n ) const |
QString | rightJustified (qsizetype width , QChar fill = QLatin1Char(' '), bool truncate = false) const |
QString | section (QChar sep , 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 | section (const QRegularExpression & re , qsizetype start , qsizetype end = -1, QString::SectionFlags flags = SectionDefault) const |
QString & | setNum (int n , int base = 10) |
QString & | setNum (short n , int base = 10) |
QString & | setNum (ushort n , int base = 10) |
QString & | setNum (uint n , int base = 10) |
QString & | setNum (long n , int base = 10) |
QString & | setNum (ulong n , int base = 10) |
QString & | setNum (qlonglong n , int base = 10) |
QString & | setNum (qulonglong n , int base = 10) |
QString & | setNum (float n , char format = 'g', int precision = 6) |
QString & | setNum (double 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 |
QString | sliced (qsizetype pos , qsizetype n ) const |
QString | sliced (qsizetype pos ) const |
QStringList | split (const QString & sep , Qt::SplitBehavior behavior = Qt::KeepEmptyParts, Qt::CaseSensitivity cs = Qt::CaseSensitive) const |
QStringList | split (QChar sep , Qt::SplitBehavior behavior = Qt::KeepEmptyParts, Qt::CaseSensitivity cs = Qt::CaseSensitive) const |
QStringList | split (const QRegularExpression & re , Qt::SplitBehavior behavior = Qt::KeepEmptyParts) const |
void | squeeze () |
bool | startsWith (const QString & s , Qt::CaseSensitivity cs = Qt::CaseSensitive) const |
bool | startsWith (QStringView str , Qt::CaseSensitivity cs = Qt::CaseSensitive) const |
bool | startsWith (QLatin1String s , Qt::CaseSensitivity cs = Qt::CaseSensitive) const |
bool | startsWith (QChar c , Qt::CaseSensitivity cs = Qt::CaseSensitive) const |
void | swap (QString & other ) |
CFStringRef | toCFString () const |
QString | toCaseFolded () const |
double | toDouble (bool * ok = nullptr) 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 |
decltype(qTokenize(*this, std::forward<Needle>(needle), flags...)) | tokenize (Needle && sep , Flags... flags ) const & |
decltype(qTokenize(std::move(*this), std::forward<Needle>(needle), flags...)) | tokenize (Needle && sep , Flags... flags ) && |
QString | trimmed () const |
void | truncate (qsizetype position ) |
const QChar * | unicode () const |
const ushort * | utf16 () const |
bool | operator!= (const char * other ) const |
bool | operator!= (const QByteArray & other ) const |
QString & | operator+= (const QString & other ) |
QString & | operator+= (QChar ch ) |
QString & | operator+= (QStringView str ) |
QString & | operator+= (QLatin1String str ) |
QString & | operator+= (const char * str ) |
QString & | operator+= (const QByteArray & ba ) |
bool | operator< (const char * other ) const |
bool | operator< (const QByteArray & other ) const |
bool | operator<= (const char * other ) const |
bool | operator<= (const QByteArray & other ) const |
QString & | operator= (QChar ch ) |
QString & | operator= (QLatin1String str ) |
QString & | operator= (const char * str ) |
bool | operator== (const char * other ) const |
bool | operator== (const QByteArray & other ) const |
bool | operator> (const char * other ) const |
bool | operator> (const QByteArray & other ) const |
bool | operator>= (const char * other ) const |
bool | operator>= (const QByteArray & other ) const |
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 (const QString & s1 , QLatin1String s2 , Qt::CaseSensitivity cs = Qt::CaseSensitive) |
int | compare (QLatin1String s1 , const QString & s2 , Qt::CaseSensitivity cs = Qt::CaseSensitive) |
int | compare (const QString & s1 , QStringView s2 , Qt::CaseSensitivity cs = Qt::CaseSensitive) |
int | compare (QStringView s1 , const QString & s2 , Qt::CaseSensitivity cs = Qt::CaseSensitive) |
QString | fromCFString (CFStringRef string ) |
QString | fromLatin1 (const char * str , qsizetype size ) |
QString | fromLatin1 (QByteArrayView str ) |
QString | fromLatin1 (const QByteArray & str ) |
QString | fromLocal8Bit (const char * str , qsizetype size ) |
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 ) |
QString | fromUtf8 (QByteArrayView str ) |
QString | fromUtf8 (const QByteArray & str ) |
QString | fromUtf8 (const char8_t * str ) |
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 ) |
int | localeAwareCompare (QStringView s1 , QStringView s2 ) |
QString | number (long n , int base = 10) |
QString | number (int n , int base = 10) |
QString | number (uint n , int base = 10) |
QString | number (ulong n , int base = 10) |
QString | number (qlonglong n , int base = 10) |
QString | number (qulonglong n , int base = 10) |
QString | number (double n , char format = 'g', int precision = 6) |
QString | vasprintf (const char * cformat , va_list ap ) |
qsizetype | erase (QString & s , const T & t ) |
qsizetype | erase_if (QString & s , Predicate pred ) |
bool | operator!= (const QString & s1 , const QString & s2 ) |
bool | operator!= (const QString & s1 , QLatin1String s2 ) |
bool | operator!= (const char * s1 , const QString & s2 ) |
QString | operator""_qs (const char16_t * str , size_t size ) |
const QString | operator+ (const QString & s1 , const QString & s2 ) |
const QString | operator+ (const QString & s1 , const char * s2 ) |
const QString | operator+ (const char * s1 , const QString & s2 ) |
bool | operator< (const QString & s1 , const QString & s2 ) |
bool | operator< (const QString & s1 , QLatin1String s2 ) |
bool | operator< (QLatin1String s1 , const QString & s2 ) |
bool | operator< (const char * s1 , const QString & s2 ) |
QDataStream & | operator<< (QDataStream & stream , const QString & string ) |
bool | operator<= (const QString & s1 , const QString & s2 ) |
bool | operator<= (const QString & s1 , QLatin1String s2 ) |
bool | operator<= (QLatin1String s1 , const QString & s2 ) |
bool | operator<= (const char * s1 , const QString & s2 ) |
bool | operator== (const QString & s1 , const QString & s2 ) |
bool | operator== (const QString & s1 , QLatin1String s2 ) |
bool | operator== (QLatin1String s1 , const QString & s2 ) |
bool | operator== (const char * s1 , const QString & s2 ) |
bool | operator> (const QString & s1 , const QString & s2 ) |
bool | operator> (const QString & s1 , QLatin1String s2 ) |
bool | operator> (QLatin1String s1 , const QString & s2 ) |
bool | operator> (const char * s1 , const QString & s2 ) |
bool | operator>= (const QString & s1 , const QString & s2 ) |
bool | operator>= (const QString & s1 , QLatin1String s2 ) |
bool | operator>= (QLatin1String s1 , const QString & s2 ) |
bool | operator>= (const char * s1 , const QString & s2 ) |
QDataStream & | operator>> (QDataStream & stream , QString & string ) |
QStringLiteral ( str ) | |
QT_NO_CAST_FROM_ASCII | |
QT_NO_CAST_TO_ASCII | |
QT_RESTRICTED_CAST_FROM_ASCII |
QString 存储字符串的 16 位 QChar ,其中各 QChar corresponds to one UTF-16 code unit. (Unicode characters with code values above 65535 are stored using surrogate pairs, i.e., two consecutive QChar )。
Unicode 是支持当今使用的大多数书写系统的国际标准。它是 US-ASCII (ANSI X3.4-1986) 和 Latin-1 (ISO 8859-1) 的超集,且所有 US-ASCII/Latin-1 字符可用于相同代码位置。
在幕后,QString 使用 隐式共享 (写时拷贝) 以缩减内存用量并避免不必要的数据拷贝。这还有助于缩减存储 16 位字符而不是 8 位字符的固有开销。
除 QString 外,Qt 还提供 QByteArray class to store raw bytes and traditional 8-bit '\0'-terminated strings. For most purposes, QString is the class you want to use. It is used throughout the Qt API, and the Unicode support ensures that your applications will be easy to translate if you want to expand your application's market at some point. The two main cases where QByteArray 是合适的,当需要存储原生二进制数据时,和当内存守恒临界时 (像在嵌入式系统)。
One way to initialize a QString is simply to pass a
const char *
到其构造函数。例如,以下代码创建包含数据 Hello 大小为 5 的 QString:
QString str = "Hello";
QString 转换
const char *
数据成 Unicode 使用
fromUtf8
() 函数。
QString 的所有函数都接受
const char *
参数,
const char *
is interpreted as a classic C-style '\0'-terminated string encoded in UTF-8. It is legal for the
const char *
parameter to be
nullptr
.
还可以将字符串数据提供成数组化的 QChar :
static const QChar data[4] = { 0x0055, 0x006e, 0x10e3, 0x03a3 }; QString str(data, 4);
QString 制作深拷贝对 QChar data, so you can modify it later without experiencing side effects. (If for performance reasons you don't want to take a deep copy of the character data, use QString::fromRawData () instead.)
另一种方式是设置字符串大小使用
resize
() 并逐字符初始化数据。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]"; }
at () 函数可以更快相比 operator[] (), because it never causes a 深拷贝 的出现。另外,使用 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
() macro which returns the given QString as a
const char *
。这相当于调用 <QString>.
toLocal8Bit
().
constData
().
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"
In the above example the replace () 函数的前 2 自变量是从哪里开始替换的位置,和应替换的字符数。
When data-modifying functions increase the size of the string, they may lead to reallocation of memory for the QString object. When this happens, QString expands by more than it immediately needs so as to have space for further expansion without reallocation until the size of the string has greatly increased.
insert (), remove () and, when replacing a sub-string with one of different size, replace () 函数可能很慢 ( 线性时间 ) for large strings, because they require moving many characters in the string by at least one position in memory.
若正逐步构建 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. After the first non-
const
operator, operations that modify QString may completely (in case of reallocation) or partially invalidate iterators and references, but other methods (such as
begin
() 或
end
()) will not. Accessing an iterator or reference after it has been invalidated leads to undefined behavior.
A frequent requirement is to remove whitespace characters from a string ('\n', '\t', ' ', etc.). If you want to remove whitespace from both ends of a QString, use the trimmed () function. If you want to remove whitespace from both ends and replace multiple consecutive whitespaces with a single space character within the string, use simplified ().
若想要查找 QString 中的特定字符 (或子字符串) 的所有出现,使用 indexOf () 或 lastIndexOf () functions. The former searches forward starting from a given index position, the latter searches backward. Both return the index position of the character or substring if they find it; otherwise, they return -1. For example, here 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 (),及类似函数。
To get an upper- or lowercase version of a string use toUpper () 或 toLower ().
字符串列表的处理是通过 QStringList 类。可以把字符串分割成字符串列表使用 split () 函数,和把字符串列表联接成单字符串采用可选分隔符使用 QStringList::join (). You can obtain a list of strings from a string list that contain a particular substring or that match a particular QRegularExpression 使用 QStringList::filter () 函数。
If you want to see if a QString starts or ends with a particular substring use startsWith () 或 endsWith (). If you simply want to check whether a QString contains a particular character or substring, use the contains () function. If you want to find out how many times a particular character or substring occurs in the string, use count ().
要获得实际字符数据指针,调用
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. Note that the comparison is based exclusively on the numeric Unicode values of the characters. It is very fast, but is not what a human would expect; the QString::localeAwareCompare () function is usually a better choice for sorting user-interface strings, when such a comparison is available.
On Unix-like platforms (including Linux, macOS and iOS), when Qt is linked with the ICU library (which it usually is), its locale-aware sorting is used. Otherwise, on macOS and iOS,
localeAwareCompare
() compares according the "Order for sorted lists" setting in the International preferences panel. On other Unix-like systems without ICU, the comparison falls back to the system library's
strcoll()
,
QString provides the following three functions that return a
const char *
版本的字符串如
QByteArray
:
toUtf8
(),
toLatin1
(),和
toLocal8Bit
().
要转换自这些编码之一,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 QLatin1String class, for example:
QString url = QLatin1String("https://www.unicode.org/");
同样,必须调用 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; }
|
For historical reasons, QString distinguishes between a null string and an empty string. A
null
string is a string that is initialized using QString's default constructor or by passing (
const char *
)0 to the constructor. An
empty
string is any string with size 0. A null string is always empty, but an empty string isn't necessarily null:
QString().isNull(); // returns true QString().isEmpty(); // returns true QString("").isNull(); // returns false QString("").isEmpty(); // returns true QString("abc").isNull(); // returns false QString("abc").isEmpty(); // returns false
所有函数除了 isNull () treat null strings the same as empty strings. For example, toUtf8 (). constData () returns a valid pointer ( not nullptr) to a '\0' character for a null string. We recommend that you always use the isEmpty () function and avoid isNull ().
当
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 will appear 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 (e.g.,
arg
(),
number
()) that represent floating-point numbers (
float
or
double
) as strings, the form of display 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. But the trivial constructor QString("Hello"), will copy the contents of the string, treating the contents as Latin-1. To avoid this one can use the QStringLiteral macro to directly create the required data at compile time. Constructing a QString out of the literal does then not cause any overhead at runtime.
A slightly less efficient way is to use QLatin1String . This class wraps a C string literal, precalculates it length at compile time and can then be used for faster comparison with QStrings and conversion to QStrings than a regular C string literal.
使用 QString
'+'
operator, it is easy to construct a complex string from multiple substrings. You will often write code like this:
QString foo; QString type = "long"; foo = QLatin1String("vector<") + type + QLatin1String(">::iterator"); if (foo.startsWith("(" + type + ") 0x")) ...
There is nothing wrong with either of these string constructions, but there are a few hidden inefficiencies. Beginning with Qt 4.6, you can eliminate them.
First, multiple uses of the
'+'
operator usually means multiple memory allocations. When concatenating
n
substrings, where
n > 2
, there can be as many as
n - 1
calls to the memory allocator.
In 4.6, an internal template class
QStringBuilder
has been added along with a few helper functions. This class is marked internal and does not appear in the documentation, because you aren't meant to instantiate it in your code. Its use will be automatic, as described below. The class is found in
src/corelib/tools/qstringbuilder.cpp
if you want to have a look at it.
QStringBuilder
uses expression templates and reimplements the
'%'
operator so that when you use
'%'
for string concatenation instead of
'+'
, multiple substring concatenations will be postponed until the final result is about to be assigned to a QString. At this point, the amount of memory required for the final result is known. The memory allocator is then called
once
to get the required space, and the substrings are copied into it one by one.
Additional efficiency is gained by inlining and reduced reference counting (the QString created from a
QStringBuilder
typically has a ref count of 1, whereas
QString::append
() 需要额外测试)。
There are 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); QLatin1String world("world"); QString message = hello % el % world % QChar('!');
A more global approach which is the most convenient but not entirely source compatible, is to this define in your .pro file:
DEFINES *= QT_USE_QSTRINGBUILDER
和
'+'
will automatically be performed as the
QStringBuilder
'%'
everywhere.
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 the 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 case where Qt will throw exceptions. If exceptions are disabled, then running out of memory is undefined behavior.
Note that the operating system may impose further limits on applications holding a lot of allocated memory, especially large, contiguous blocks. Such considerations, the configuration of such behavior or any mitigation are outside the scope of the Qt API.
另请参阅 fromRawData (), QChar , QStringView , QLatin1String ,和 QByteArray .
Qt 样式同义词 QString::const_iterator .
Qt 样式同义词 QString::iterator .
此枚举描述 Unicode 文本的各种规范化形式。
常量 | 值 | 描述 |
---|---|---|
QString::NormalizationForm_D
|
0
|
典型分解 |
QString::NormalizationForm_C
|
1
|
典型分解,紧接着是典型合成 |
QString::NormalizationForm_KD
|
2
|
兼容性分解 |
QString::NormalizationForm_KC
|
3
|
兼容性分解,紧接着是典型合成 |
另请参阅 normalized () 和 Unicode 标准附录 #15 .
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::iterator .
The QString::const_pointer typedef provides an STL-style const pointer to a QString 元素 ( QChar ).
[since 5.6]
QString::
const_reverse_iterator
该 typedef 在 Qt 5.6 引入。
另请参阅 QString::reverse_iterator and QString::const_iterator .
另请参阅 QString::const_iterator .
The QString::pointer typedef provides an STL-style pointer to a QString 元素 ( QChar ).
[since 5.6]
QString::
reverse_iterator
该 typedef 在 Qt 5.6 引入。
另请参阅 QString::const_reverse_iterator and QString::iterator .
[since 6.0]
template <typename Needle, typename Flags>
decltype
(
qTokenize
(
std::move
(*
this
),
std::forward
<
Needle
>(
needle
),
flags
...)) QString::
tokenize
(
Needle
&&
sep
,
Flags
...
flags
) &&
[since 6.0]
template <typename Needle, typename Flags>
decltype
(
qTokenize
(*
this
,
std::forward
<
Needle
>(
needle
),
flags
...)) QString::
tokenize
(
Needle
&&
sep
,
Flags
...
flags
) const &
[since 6.0]
template <typename Needle, typename Flags>
decltype
(
qTokenize
(*
this
,
std::forward
<
Needle
>(
needle
),
flags
...)) 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 引入。
另请参阅 QStringTokenizer and qTokenize ().
[since 5.14]
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
%N
with the next-lowest
N
etc.
Args
can consist of anything that implicitly converts to
QString
,
QStringView
or
QLatin1String
.
In addition, the following types are also supported: QChar , QLatin1Char .
该函数在 Qt 5.14 引入。
另请参阅 QString::arg ().
Constructs a string initialized with the byte array ba . The given byte array is converted to Unicode using fromUtf8 (). Stops copying at the first 0 character, otherwise copies the entire byte array.
You can disable this constructor by defining QT_NO_CAST_FROM_ASCII when you compile your applications. This can be useful if you want to ensure that all user-visible strings go through QObject::tr (), for example.
另请参阅 fromLatin1 (), fromLocal8Bit (),和 fromUtf8 ().
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 5.2]
QString::
QString
(
QString
&&
other
)
Move-constructs a QString instance, making it point at the same object that other 所指向的。
该函数在 Qt 5.2 引入。
构造副本为 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= ().
[since 6.1]
template <typename> 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 ().
Constructs a copy of the Latin-1 string str .
另请参阅 fromLatin1 ().
Constructs a string of the given size with every character set to ch .
另请参阅 fill ().
Constructs a string of size 1 containing the character ch .
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 ().
Constructs a null string. Null strings are also empty.
另请参阅 isEmpty ().
此函数重载 operator=()。
赋值 ba to this string. The byte array is converted to Unicode using the fromUtf8 () function. This function stops conversion at the first NUL character found, or the end of the ba byte array.
可以禁用此运算符通过定义 QT_NO_CAST_FROM_ASCII when you compile your applications. This can be useful if you want to ensure that all user-visible strings go through QObject::tr (), for example.
[since 5.2]
QString
&QString::
operator=
(
QString
&&
other
)
移动赋值 other 到此 QString 实例。
该函数在 Qt 5.2 引入。
赋值 other to this string and returns a reference to this string.
销毁字符串。
追加字符串 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 ().
此函数重载 append()。
追加字符 ch 到此字符串。
[since 5.0]
QString
&QString::
append
(const
QChar
*
str
,
qsizetype
len
)
此函数重载 append()。
追加 len 字符来自 QChar array str 到此字符串。
该函数在 Qt 5.0 引入。
此函数重载 append()。
追加 Latin-1 字符串 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.
此函数重载 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.
返回字符串副本,替换最小编号位置标记为字符串
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.
此函数重载 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.
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 .
此函数重载 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.
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 .
此函数重载 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.
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 .
此函数重载 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.
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 .
此函数重载 arg()。
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 .
此函数重载 arg()。
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 .
此函数重载 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.
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 .
此函数重载 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.
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 .
此函数重载 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 .
此函数重载 arg()。
a 自变量被解释成 Latin-1 字符。
此函数重载 arg()。
[since 5.10]
QString
QString::
arg
(
QStringView
a
,
int
fieldWidth
= 0,
QChar
fillChar
= QLatin1Char(' ')) 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.
该函数在 Qt 5.10 引入。
[since 5.10]
QString
QString::
arg
(
QLatin1String
a
,
int
fieldWidth
= 0,
QChar
fillChar
= QLatin1Char(' ')) 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.
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.
该函数在 Qt 5.10 引入。
[static, since 5.5]
QString
QString::
asprintf
(const
char
*
cformat
, ...)
安全地构建格式化字符串从格式字符串 cformat 和任意自变量列表。
格式字符串支持转换说明符、长度修饰符及由标准 C++ 库 printf() 提供的标志。
cformat
字符串和
%s
自变量必须是 UTF-8 编码。
注意:
%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 () 函数代替。这允许翻译者控制置换次序。
该函数在 Qt 5.5 引入。
另请参阅 arg ().
返回字符按给定索引 position 在字符串中。
position must be a valid index position in the string (i.e., 0 <= position < size ()).
另请参阅 operator[] ().
[since 5.10]
QChar
QString::
back
() const
返回字符串中的最后一个字符。如同
at(size() - 1)
.
此函数为兼容 STL (标准模板库) 提供。
警告: 在空字符串调用此函数,将构成未定义行为。
该函数在 Qt 5.10 引入。
另请参阅 front (), at (),和 operator[] ().
[since 5.10]
QChar
&QString::
back
()
Returns a reference to the last character in the string. Same as
operator[](size() - 1)
.
此函数为兼容 STL (标准模板库) 提供。
警告: 在空字符串调用此函数,将构成未定义行为。
该函数在 Qt 5.10 引入。
另请参阅 front (), at (),和 operator[] ().
返回 STL 样式迭代器 指向字符串中的首个字符。
警告: 返回迭代器不验证当分离时或当 QString 被修改。
另请参阅 constBegin () 和 end ().
此函数重载 begin()。
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.
[since 5.0]
QString::const_iterator
QString::
cbegin
() const
返回常量 STL 样式迭代器 指向字符串中的首个字符。
警告: 返回迭代器不验证当分离时或当 QString 被修改。
该函数在 Qt 5.0 引入。
[since 5.0]
QString::const_iterator
QString::
cend
() const
返回常量 STL 样式迭代器 仅仅指向字符串中最后一个字符的后面。
警告: 返回迭代器不验证当分离时或当 QString 被修改。
该函数在 Qt 5.0 引入。
移除 n 个字符从字符串末尾起。
若 n >= size (),结果为空字符串;若 n 为负,相当于传递 0。
范例:
QString str("LOGOUT\r\n"); str.chop(2); // str == "LOGOUT"
若想要移除字符从 beginning 对于字符串,使用 remove () 代替。
另请参阅 truncate (), resize (), remove (),和 QStringView::chop ().
[since 5.10]
QString
QString::
chopped
(
qsizetype
len
) const
返回字符串包含 size () - len leftmost characters of this string.
注意: 行为未定义若 len 为负或大于 size ().
该函数在 Qt 5.10 引入。
另请参阅 endsWith (), first (), last (), sliced (), chop (),和 truncate ().
清零字符串内容,并使之为 null。
[static]
int
QString::
compare
(const
QString
&
s1
, const
QString
&
s2
,
Qt::CaseSensitivity
cs
= Qt::CaseSensitive)
比较 s1 with s2 and returns an integer less than, equal to, or greater than zero if s1 is less than, equal to, or greater than s2 .
若 cs is Qt::CaseSensitive , the comparison is case sensitive; otherwise the comparison is case insensitive.
Case sensitive comparison is based exclusively on the numeric Unicode values of the characters and is very fast, but is not what a human would expect. Consider sorting user-visible strings with localeAwareCompare ().
int x = QString::compare("aUtO", "AuTo", Qt::CaseInsensitive); // x == 0 int y = QString::compare("auto", "Car", Qt::CaseSensitive); // y > 0 int z = QString::compare("auto", "Car", Qt::CaseInsensitive); // z < 0
另请参阅 operator== (), operator< (), operator> (),和 Comparing Strings .
此函数重载 compare()。
Lexically compares this string with the other string and returns an integer less than, equal to, or greater than zero if this string is less than, equal to, or greater than the other string.
如同 compare(*this, other , cs ).
此函数重载 compare()。
如同 compare(*this, other , cs ).
[since 5.12]
int
QString::
compare
(
QStringView
s
,
Qt::CaseSensitivity
cs
= Qt::CaseSensitive) const
此函数重载 compare()。
履行比较为此与 s ,使用区分大小写设置 cs .
该函数在 Qt 5.12 引入。
[since 5.14]
int
QString::
compare
(
QChar
ch
,
Qt::CaseSensitivity
cs
= Qt::CaseSensitive) const
此函数重载 compare()。
履行比较为此与 ch ,使用区分大小写设置 cs .
该函数在 Qt 5.14 引入。
[static]
int
QString::
compare
(const
QString
&
s1
,
QLatin1String
s2
,
Qt::CaseSensitivity
cs
= Qt::CaseSensitive)
此函数重载 compare()。
履行比较为 s1 and s2 ,使用区分大小写设置 cs .
[static]
int
QString::
compare
(
QLatin1String
s1
, const
QString
&
s2
,
Qt::CaseSensitivity
cs
= Qt::CaseSensitive)
此函数重载 compare()。
履行比较为 s1 and s2 ,使用区分大小写设置 cs .
[static]
int
QString::
compare
(const
QString
&
s1
,
QStringView
s2
,
Qt::CaseSensitivity
cs
= Qt::CaseSensitive)
此函数重载 compare()。
[static]
int
QString::
compare
(
QStringView
s1
, const
QString
&
s2
,
Qt::CaseSensitivity
cs
= Qt::CaseSensitive)
此函数重载 compare()。
返回常量 STL 样式迭代器 指向字符串中的首个字符。
警告: 返回迭代器不验证当分离时或当 QString 被修改。
返回指针指向的数据存储在 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 ().
返回常量 STL 样式迭代器 仅仅指向字符串中最后一个字符的后面。
警告: 返回迭代器不验证当分离时或当 QString 被修改。
另请参阅 constBegin () 和 end ().
返回
true
若此字符串包含出现的字符串
str
;否则返回
false
.
若 cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.
范例:
QString str = "Peter Pan"; str.contains("peter", Qt::CaseInsensitive); // returns true
此函数重载 contains()。
返回
true
若此字符串包含出现字符
ch
;否则返回
false
.
[since 5.3]
bool
QString::
contains
(
QLatin1String
str
,
Qt::CaseSensitivity
cs
= Qt::CaseSensitive) const
此函数重载 contains()。
返回
true
若此字符串包含出现的 latin-1 字符串
str
;否则返回
false
.
该函数在 Qt 5.3 引入。
[since 5.14]
bool
QString::
contains
(
QStringView
str
,
Qt::CaseSensitivity
cs
= Qt::CaseSensitive) const
此函数重载 contains()。
返回
true
若此字符串包含出现的字符串视图
str
;否则返回
false
.
若 cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.
该函数在 Qt 5.14 引入。
[since 5.1]
bool
QString::
contains
(const
QRegularExpression
&
re
,
QRegularExpressionMatch
*
rmatch
= nullptr) const
返回
true
若正则表达式
re
匹配此字符串中的某些地方;否则返回
false
.
若匹配成功且
rmatch
不是
nullptr
,它还把匹配结果写入
QRegularExpressionMatch
对象指向的
rmatch
.
该函数在 Qt 5.1 引入。
另请参阅 QRegularExpression::match ().
返回 (潜在重叠) 出现数对于字符串 str 在此字符串中。
若 cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.
另请参阅 contains () 和 indexOf ().
此函数重载 count()。
如同 size ().
此函数重载 count()。
返回出现数对于字符 ch 在字符串中。
若 cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.
另请参阅 contains () 和 indexOf ().
[since 6.0]
qsizetype
QString::
count
(
QStringView
str
,
Qt::CaseSensitivity
cs
= Qt::CaseSensitive) const
此函数重载 count()。
返回 (潜在重叠) 出现数对于字符串视图 str 在此字符串中。
若 cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.
该函数在 Qt 6.0 引入。
另请参阅 contains () 和 indexOf ().
[since 5.0]
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 .
该函数在 Qt 5.0 引入。
另请参阅 QRegularExpression::globalMatch ().
[since 5.6]
QString::const_reverse_iterator
QString::
crbegin
() const
返回常量 STL-style reverse iterator pointing to the first character in the string, in reverse order.
警告: 返回迭代器不验证当分离时或当 QString 被修改。
该函数在 Qt 5.6 引入。
另请参阅 begin (), rbegin (),和 rend ().
[since 5.6]
QString::const_reverse_iterator
QString::
crend
() const
返回常量 STL-style reverse iterator pointing just after the last character in the string, in reverse order.
警告: 返回迭代器不验证当分离时或当 QString 被修改。
该函数在 Qt 5.6 引入。
另请参阅 end (), rend (),和 rbegin ().
返回指针指向的数据存储在 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[] ().
这是重载函数。
注意: 返回字符串不能以 \0 结尾。使用 size () 以确定数组的长度。
另请参阅 fromRawData ().
返回 STL 样式迭代器 仅仅指向字符串中最后一个字符的后面。
警告: 返回迭代器不验证当分离时或当 QString 被修改。
此函数重载 end()。
返回
true
若字符串结尾为
s
;否则返回
false
.
若 cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.
QString str = "Bananas"; str.endsWith("anas"); // returns true str.endsWith("pple"); // returns false
另请参阅 startsWith ().
[since 5.10]
bool
QString::
endsWith
(
QStringView
str
,
Qt::CaseSensitivity
cs
= Qt::CaseSensitive) const
此函数重载 endsWith()。
返回
true
若字符串结尾为字符串视图
str
;否则返回
false
.
若 cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.
该函数在 Qt 5.10 引入。
另请参阅 startsWith ().
此函数重载 endsWith()。
返回
true
若字符串结尾为
c
;否则返回
false
.
此函数重载 endsWith()。
[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 referred to by last before the erase.
该函数在 Qt 6.1 引入。
将字符串中的每个字符设为字符 ch 。若 size 不同于 -1 (默认),重置字符串大小到 size 事先。
范例:
QString str = "Berlin"; str.fill('z'); // str == "zzzzzz" str.fill('A', 2); // str == "AA"
另请参阅 resize ().
[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 ().
[static, since 5.2]
QString
QString::
fromCFString
(
CFStringRef
string
)
构造新的 QString 包含副本 string CFString.
注意: 此函数只可用于 macOS 和 iOS。
该函数在 Qt 5.2 引入。
[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 .
该函数在 Qt 6.0 引入。
[static, since 5.0]
template <typename>
QString
QString::
fromLatin1
(const
QByteArray
&
str
)
这是重载函数。
返回 QString 初始采用 Latin-1 字符串 str .
该函数在 Qt 5.0 引入。
[static]
QString
QString::
fromLocal8Bit
(const
char
*
str
,
qsizetype
size
)
返回 QString 初始采用前 size 个字符对于 8 位字符串 str .
若
size
is
-1
,
strlen(str)
被使用,取而代之。
On Unix systems this is equivalen to fromUtf8 (), on Windows the systems current code page is being used.
另请参阅 toLocal8Bit (), fromLatin1 (),和 fromUtf8 ().
[static, since 6.0]
QString
QString::
fromLocal8Bit
(
QByteArrayView
str
)
这是重载函数。
返回 QString initialized with the 8-bit string str .
该函数在 Qt 6.0 引入。
[static, since 5.0]
template <typename>
QString
QString::
fromLocal8Bit
(const
QByteArray
&
str
)
这是重载函数。
返回 QString initialized with the 8-bit string str .
该函数在 Qt 5.0 引入。
[static, since 5.2]
QString
QString::
fromNSString
(const
NSString
*
string
)
构造新的 QString 包含副本 string NSString.
注意: 此函数只可用于 macOS 和 iOS。
该函数在 Qt 5.2 引入。
[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 converted to Unicode using the fromUtf8 () 函数。
另请参阅 fromLatin1 (), fromLocal8Bit (), fromUtf8 (),和 QByteArray::fromStdString ().
[static, since 5.5]
QString
QString::
fromStdU16String
(const
std::u16string
&
str
)
返回副本为 str string. The given string is assumed to be encoded in UTF-16.
该函数在 Qt 5.5 引入。
另请参阅 fromUtf16 (), fromStdWString (),和 fromStdU32String ().
[static, since 5.5]
QString
QString::
fromStdU32String
(const
std::u32string
&
str
)
返回副本为 str string. The given string is assumed to be encoded in UCS-4.
该函数在 Qt 5.5 引入。
另请参阅 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, since 5.3]
QString
QString::
fromUcs4
(const
char32_t
*
unicode
,
qsizetype
size
= -1)
返回 QString 初始采用前 size characters of the Unicode string unicode (ISO-10646-UCS-4 encoded).
若 size is -1 (default), unicode must be \0'-terminated.
该函数在 Qt 5.3 引入。
另请参阅 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 .
该函数在 Qt 6.0 引入。
[static, since 5.0]
template <typename>
QString
QString::
fromUtf8
(const
QByteArray
&
str
)
这是重载函数。
返回 QString initialized with the UTF-8 string str .
该函数在 Qt 5.0 引入。
[static, since 6.1]
template <typename>
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]
template <typename>
QString
QString::
fromUtf8
(const
char8_t
*
str
,
qsizetype
size
)
这是重载函数。
This overload is only available when compiling in C++20 mode.
该函数在 Qt 6.0 引入。
[static, since 5.3]
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 *, int) or QString (const QChar *) if possible.
QString makes a deep copy of the Unicode data.
该函数在 Qt 5.3 引入。
另请参阅 utf16 (), setUtf16 (),和 fromStdU16String ().
[static]
QString
QString::
fromWCharArray
(const
wchar_t
*
string
,
qsizetype
size
= -1)
返回副本为 string , where the encoding of string depends on the size of wchar. If wchar is 4 bytes, the string is interpreted as UCS-4, if wchar is 2 bytes it is interpreted as UTF-16.
若 size is -1 (default), the string must be '\0'-terminated.
另请参阅 fromUtf16 (), fromLatin1 (), fromLocal8Bit (), fromUtf8 (), fromUcs4 (),和 fromStdWString ().
[since 5.10]
QChar
QString::
front
() const
Returns the first character in the string. Same as
at(0)
.
此函数为兼容 STL (标准模板库) 提供。
警告: 在空字符串调用此函数,将构成未定义行为。
该函数在 Qt 5.10 引入。
另请参阅 back (), at (),和 operator[] ().
[since 5.10]
QChar
&QString::
front
()
Returns a reference to the first character in the string. Same as
operator[](0)
.
此函数为兼容 STL (标准模板库) 提供。
警告: 在空字符串调用此函数,将构成未定义行为。
该函数在 Qt 5.10 引入。
另请参阅 back (), at (),和 operator[] ().
Returns the index position of the first occurrence of the string str in this string, searching forward from index position from . Returns -1 if str 找不到。
若 cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.
范例:
QString x = "sticky question"; QString y = "sti"; x.indexOf(y); // returns 0 x.indexOf(y, 1); // returns 10 x.indexOf(y, 10); // returns 10 x.indexOf(y, 11); // returns -1
若 from is -1, the search starts at the last character; if it is -2, at the next to last character and so on.
另请参阅 lastIndexOf (), contains (),和 count ().
此函数重载 indexOf()。
Returns the index position of the first occurrence of the character ch in the string, searching forward from index position from . Returns -1 if ch could not be found.
Returns the index position of the first occurrence of the string str in this string, searching forward from index position from . Returns -1 if str 找不到。
若 cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.
范例:
QString x = "sticky question"; QString y = "sti"; x.indexOf(y); // returns 0 x.indexOf(y, 1); // returns 10 x.indexOf(y, 10); // returns 10 x.indexOf(y, 11); // returns -1
若 from is -1, the search starts at the last character; if it is -2, at the next to last character and so on.
另请参阅 lastIndexOf (), contains (),和 count ().
[since 5.14]
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 (default), the search is case sensitive; otherwise the search is case insensitive.
若 from is -1, the search starts at the last character; if it is -2, at the next to last character and so on.
该函数在 Qt 5.14 引入。
另请参阅 QStringView::indexOf (), lastIndexOf (), contains (),和 count ().
[since 5.5]
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
该函数在 Qt 5.5 引入。
插入字符串 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 ().
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 .
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 .
[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 引入。
This function overloads insert().
Inserts the Latin-1 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 .
[since 5.5]
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 有定义。
该函数在 Qt 5.5 引入。
[since 5.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 有定义。
该函数在 Qt 5.5 引入。
返回
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 ().
[since 5.12]
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.
该函数在 Qt 5.12 引入。
另请参阅 QChar::toLower () 和 isUpper ().
返回
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 ().
返回
true
if the string is read right to left.
另请参阅 QStringView::isRightToLeft ().
[since 5.12]
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.
该函数在 Qt 5.12 引入。
另请参阅 QChar::toUpper () 和 isLower ().
[since 5.15]
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.
该函数在 Qt 5.15 引入。
另请参阅 QStringView::isValidUtf16 ().
[since 6.0]
QString
QString::
last
(
qsizetype
n
) const
Returns the string that contains the last 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 ().
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 from is -2, at the next to last character and so on. Returns -1 if str 找不到。
若 cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.
范例:
QString x = "crazy azimuths"; QString y = "az"; x.lastIndexOf(y); // returns 6 x.lastIndexOf(y, 6); // returns 6 x.lastIndexOf(y, 5); // returns 2 x.lastIndexOf(y, 1); // returns -1
注意:
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 ().
This function overloads lastIndexOf().
Returns the index position of the last occurrence of the character ch , searching backward from position from .
[since 6.2]
qsizetype
QString::
lastIndexOf
(
QLatin1String
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 (default), the search is case sensitive; otherwise the search is case insensitive.
范例:
QString x = "crazy azimuths"; QString y = "az"; x.lastIndexOf(y); // returns 6 x.lastIndexOf(y, 6); // returns 6 x.lastIndexOf(y, 5); // returns 2 x.lastIndexOf(y, 1); // returns -1
该函数在 Qt 6.2 引入。
另请参阅 indexOf (), contains (),和 count ().
This function overloads lastIndexOf().
Returns the index position of the last occurrence of the string str in this string, searching backward from index position from 。若 from is -1, the search starts at the last character; if from is -2, at the next to last character and so on. Returns -1 if str 找不到。
若 cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.
范例:
QString x = "crazy azimuths"; QString y = "az"; x.lastIndexOf(y); // returns 6 x.lastIndexOf(y, 6); // returns 6 x.lastIndexOf(y, 5); // returns 2 x.lastIndexOf(y, 1); // returns -1
注意:
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 ().
[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 (default), the search is case sensitive; otherwise the search is case insensitive.
范例:
QString x = "crazy azimuths"; QString y = "az"; x.lastIndexOf(y); // returns 6 x.lastIndexOf(y, 6); // returns 6 x.lastIndexOf(y, 5); // returns 2 x.lastIndexOf(y, 1); // returns -1
该函数在 Qt 6.2 引入。
另请参阅 indexOf (), contains (),和 count ().
[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 (default), the search is case sensitive; otherwise the search is case insensitive.
该函数在 Qt 6.2 引入。
另请参阅 indexOf (), contains (),和 count ().
[since 5.14]
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 from is -2, at the next to last character and so on. Returns -1 if str 找不到。
若 cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.
注意:
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.
该函数在 Qt 5.14 引入。
另请参阅 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 5.5]
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 from is -2, at the next to last character and so on. 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 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.
该函数在 Qt 5.5 引入。
Returns a substring that contains the n leftmost characters of the string.
若知道 n 不可以超出边界,使用 first () 代替在新代码中,因为它更快。
返回整个字符串若 n >= size (),或小于 0。
另请参阅 first (), last (), startsWith (), chopped (), chop (),和 truncate ().
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 ().
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 .
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 .
[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 .
[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 .
返回字符串包含 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 ().
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
(
int
n
,
int
base
= 10)
这是重载函数。
[static]
QString
QString::
number
(
uint
n
,
int
base
= 10)
这是重载函数。
[static]
QString
QString::
number
(
ulong
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
(
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 .
前置字符串 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"
This function overloads prepend().
前置字符 ch 到此字符串。
[since 5.5]
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.
该函数在 Qt 5.5 引入。
[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 引入。
This function overloads prepend().
Prepends the Latin-1 string 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.
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.
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 ().
这是重载函数。
Appends the given ch character onto the end of this string.
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 ().
这是重载函数。
Prepends the given ch character to the beginning of this string.
[since 5.6]
QString::reverse_iterator
QString::
rbegin
()
返回 STL-style reverse iterator pointing to the first character in the string, in reverse order.
警告: 返回迭代器不验证当分离时或当 QString 被修改。
该函数在 Qt 5.6 引入。
另请参阅 begin (), crbegin (),和 rend ().
[since 5.6]
QString::const_reverse_iterator
QString::
rbegin
() const
这是重载函数。
该函数在 Qt 5.6 引入。
移除 n characters from the string, starting at the given position index, and returns a reference to the string.
若指定 position index is within the string, but position + n is beyond the end of the string, the string is truncated at the specified position .
QString s = "Montreal"; s.remove(1, 4); // s == "Meal"
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.
Removes every occurrence of the character ch in this string, and returns a reference to this string.
若 cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.
范例:
QString t = "Ali Baba"; t.remove(QChar('a'), Qt::CaseInsensitive); // t == "li Bb"
这如同
replace(ch, "", cs)
.
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 5.11]
QString
&QString::
remove
(
QLatin1String
str
,
Qt::CaseSensitivity
cs
= Qt::CaseSensitive)
这是重载函数。
Removes every occurrence of the given str string in this string, and returns a reference to this string.
若 cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.
这如同
replace(str, "", cs)
.
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.
该函数在 Qt 5.11 引入。
另请参阅 replace ().
Removes every occurrence of the given str string in this string, and returns a reference to this string.
若 cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.
这如同
replace(str, "", cs)
.
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 5.0]
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.
该函数在 Qt 5.0 引入。
另请参阅 indexOf (), lastIndexOf (),和 replace ().
[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 5.6]
QString::reverse_iterator
QString::
rend
()
返回 STL-style reverse iterator pointing just after the last character in the string, in reverse order.
警告: 返回迭代器不验证当分离时或当 QString 被修改。
该函数在 Qt 5.6 引入。
另请参阅 end (), crend (),和 rbegin ().
[since 5.6]
QString::const_reverse_iterator
QString::
rend
() const
这是重载函数。
该函数在 Qt 5.6 引入。
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"
替换 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!"
此函数重载 replace()。
替换 n characters beginning at index position with the character after 并返回此字符串的引用。
此函数重载 replace()。
替换 n characters beginning at index position with the first size characters of the QChar array unicode 并返回此字符串的引用。
此函数重载 replace()。
Replaces every occurrence of the character before with the character after 并返回此字符串的引用。
若 cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.
此函数重载 replace()。
Replaces each occurrence in this string of the first blen 字符的 before with the first alen 字符的 after 并返回此字符串的引用。
若 cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.
此函数重载 replace()。
Replaces every occurrence of the string before 采用字符串 after 并返回此字符串的引用。
若 cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.
注意: The text is not rescanned after a replacement.
此函数重载 replace()。
Replaces every occurrence of the string before 采用字符串 after 并返回此字符串的引用。
若 cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.
注意: The text is not rescanned after a replacement.
此函数重载 replace()。
Replaces every occurrence of the string before 采用字符串 after 并返回此字符串的引用。
若 cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.
注意: The text is not rescanned after a replacement.
此函数重载 replace()。
Replaces every occurrence of the string before 采用字符串 after 并返回此字符串的引用。
若 cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.
范例:
QString str = "colour behaviour flavour neighbour"; str.replace(QString("ou"), QString("o")); // str == "color behavior flavor neighbor"
注意: The replacement text is not rescanned after it is inserted.
范例:
QString equis = "xxxxxx"; equis.replace("xx", "x"); // equis == "xxx"
此函数重载 replace()。
Replaces every occurrence of the character ch in the string with after 并返回此字符串的引用。
若 cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.
此函数重载 replace()。
Replaces every occurrence of the character c 采用字符串 after 并返回此字符串的引用。
若 cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.
注意: The text is not rescanned after a replacement.
[since 5.0]
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}."
该函数在 Qt 5.0 引入。
另请参阅 indexOf (), lastIndexOf (), remove (), QRegularExpression ,和 QRegularExpressionMatch .
Ensures the string has space for at least size 字符。
If you know in advance how large the string will be, you can call this function to save repeated reallocation in the course of 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 really need, which 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 ().
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 ().
[since 5.7]
void
QString::
resize
(
qsizetype
size
,
QChar
fillChar
)
这是重载函数。
不像 resize (qsizetype), this overload initializes the new characters to fillChar :
QString t = "Hello"; r.resize(t.size() + 10, 'X'); // t == "HelloXXXXXXXXXX"
该函数在 Qt 5.7 引入。
Returns a substring that contains the n rightmost characters of the string.
若知道 n 不可以超出边界,使用 last () 代替在新代码中,因为它更快。
返回整个字符串若 n >= size (),或小于 0。
另请参阅 endsWith (), last (), first (), sliced (), chopped (), chop (),和 truncate ().
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 ().
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.
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 ().
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 ().
[since 5.0]
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.
该函数在 Qt 5.0 引入。
另请参阅 split () 和 simplified ().
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 ().
这是重载函数。
这是重载函数。
这是重载函数。
这是重载函数。
这是重载函数。
这是重载函数。
这是重载函数。
这是重载函数。
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 ().
这是重载函数。
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 .
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 ().
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 ().
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 ().
[since 5.10]
void
QString::
shrink_to_fit
()
此函数为兼容 STL (标准模板库) 提供。它相当于 squeeze ().
该函数在 Qt 5.10 引入。
另请参阅 squeeze ().
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 ().
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'
[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 ().
[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 (), sliced (), chopped (), chop (),和 truncate ().
[since 5.14]
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(QLatin1Char(',')); // list1: [ "a", "", "b", "c" ] QStringList list2 = str.split(QLatin1Char(','), 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(QLatin1Char('/')); // parts: {"", "a", "b", "c", ""}
该函数在 Qt 5.14 引入。
另请参阅 QStringList::join () 和 section ().
[since 5.14]
QStringList
QString::
split
(
QChar
sep
,
Qt::SplitBehavior
behavior
= Qt::KeepEmptyParts,
Qt::CaseSensitivity
cs
= Qt::CaseSensitive) const
这是重载函数。
该函数在 Qt 5.14 引入。
[since 5.14]
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", "." ]
该函数在 Qt 5.14 引入。
另请参阅 QStringList::join () 和 section ().
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 ().
返回
true
if the string starts with
s
;否则返回
false
.
若 cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.
QString str = "Bananas"; str.startsWith("Ban"); // returns true str.startsWith("Car"); // returns false
另请参阅 endsWith ().
[since 5.10]
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 (default), the search is case-sensitive; otherwise the search is case insensitive.
该函数在 Qt 5.10 引入。
另请参阅 endsWith ().
This function overloads startsWith().
This function overloads startsWith().
返回
true
if the string starts with
c
;否则返回
false
.
交换字符串 other with this string. This operation is very fast and never fails.
[since 5.2]
CFStringRef
QString::
toCFString
() const
Creates a CFString from a QString .
The caller owns the CFString and is responsible for releasing it.
注意: 此函数只可用于 macOS 和 iOS。
该函数在 Qt 5.2 引入。
Returns the case folded equivalent of the string. For most Unicode characters this is the same as toLower ().
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
警告: 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 ().
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
.
警告: 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 ().
[since 5.0]
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>"
该函数在 Qt 5.0 引入。
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; 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
此函数忽略前导和结尾空格。
另请参阅 number (), toUInt (), toDouble (),和 QLocale::toInt ().
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 .
Returns the local 8-bit representation of the string as a QByteArray . The returned byte array is undefined if the string contains characters not supported by the local 8-bit encoding.
On Unix systems this is equivalen to toUtf8 (), on Windows the systems current code page is being used.
If this string contains any characters that cannot be encoded in the locale, the returned byte array is undefined. Those characters may be suppressed or replaced by another.
另请参阅 fromLocal8Bit (), toLatin1 (), toUtf8 (),和 QStringEncoder .
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; 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
此函数忽略前导和结尾空格。
另请参阅 number (), toULong (), toInt (),和 QLocale::toInt ().
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; 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
此函数忽略前导和结尾空格。
另请参阅 number (), toULongLong (), toInt (),和 QLocale::toLongLong ().
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 ().
[since 5.2]
NSString
*QString::
toNSString
() const
Creates a NSString from a QString .
The NSString is autoreleased.
注意: 此函数只可用于 macOS 和 iOS。
该函数在 Qt 5.2 引入。
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; 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
此函数忽略前导和结尾空格。
另请参阅 number (), toUShort (), toInt (),和 QLocale::toShort ().
返回 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 ().
[since 5.5]
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 () 方法。
该函数在 Qt 5.5 引入。
另请参阅 utf16 (), toStdWString (),和 toStdU32String ().
[since 5.5]
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 () 方法。
该函数在 Qt 5.5 引入。
另请参阅 toUcs4 (), toStdWString (),和 toStdU16String ().
Returns a std::wstring object with the data contained in this QString . The std::wstring is encoded in utf16 on platforms where wchar_t is 2 bytes wide (e.g. windows) and in ucs4 on platforms where wchar_t is 4 bytes wide (most Unix systems).
This method is mostly useful to pass a QString to a function that accepts a std::wstring object.
另请参阅 utf16 (), toLatin1 (), toUtf8 (), toLocal8Bit (), toStdU16String (),和 toStdU32String ().
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; 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
此函数忽略前导和结尾空格。
另请参阅 number (), toInt (),和 QLocale::toUInt ().
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; 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
此函数忽略前导和结尾空格。
另请参阅 number () 和 QLocale::toUInt ().
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; 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
此函数忽略前导和结尾空格。
另请参阅 number (), toLongLong (),和 QLocale::toULongLong ().
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; 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
此函数忽略前导和结尾空格。
另请参阅 number (), toShort (),和 QLocale::toUShort ().
Returns a UCS-4/UTF-32 representation of the string as a QList <uint>.
UCS-4 is a Unicode codec and therefore it is lossless. All characters from this string will be encoded in UCS-4. Any invalid sequence of code units in this string is replaced by the Unicode's replacement character (
QChar::ReplacementCharacter
, which corresponds to
U+FFFD
).
The returned list is not \0'-terminated.
另请参阅 fromUtf8 (), toUtf8 (), toLatin1 (), toLocal8Bit (), QStringEncoder , fromUcs4 (),和 toWCharArray ().
Returns an uppercase copy of the string.
QString str = "TeXt"; str = str.toUpper(); // str == "TEXT"
The case conversion will always happen in the 'C' locale. For locale-dependent case folding use QLocale::toUpper ()
另请参阅 toLower () 和 QLocale::toLower ().
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 .
填充 array with the data contained in this QString object. The array is encoded in UTF-16 on platforms where wchar_t is 2 bytes wide (e.g. windows) and in UCS-4 on platforms where wchar_t is 4 bytes wide (most Unix systems).
array has to be allocated by the caller and contain enough space to hold the complete string (allocating the array with the same length as the string is always sufficient).
This function returns the actual length of the string in array .
注意: This function does not append a null character to the array.
另请参阅 utf16 (), toUcs4 (), toLatin1 (), toUtf8 (), toLocal8Bit (), toStdWString (),和 QStringView::toWCharArray ().
返回从开始到结束之间,已移除空白的字符串。
空白意味着任何字符其。
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 ().
截取字符串按给定 position 索引。
若指定 position 索引超出字符串末尾,什么都不发生。
范例:
QString str = "Vladivostok"; str.truncate(4); // str == "Vlad"
若 position 为负,相当于传递 0。
另请参阅 chop (), resize (), first (),和 QStringView::truncate ().
Returns a Unicode representation of the string. The result remains valid until the string is modified.
注意: 返回字符串不能以 \0 结尾。使用 size () 以确定数组的长度。
另请参阅 setUnicode (), utf16 (),和 fromRawData ().
返回 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, since 5.5]
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 .
该函数在 Qt 5.5 引入。
另请参阅 asprintf ().
This function overloads operator!=().
other const char pointer is converted to a QString 使用 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.
This function overloads operator!=().
other byte array is converted to a QString 使用 fromUtf8 () function. If any NUL characters ('\0') are embedded in the byte array, they will be included in the transformation.
可以禁用此运算符通过定义 QT_NO_CAST_FROM_ASCII when you compile your applications. This can be useful if you want to ensure that all user-visible strings go through QObject::tr (), for example.
追加字符串 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.
This function overloads operator+=().
追加字符 ch to the string.
[since 6.0]
QString
&QString::
operator+=
(
QStringView
str
)
This function overloads operator+=().
Appends the string view str 到此字符串。
该函数在 Qt 6.0 引入。
This function overloads operator+=().
追加 Latin-1 字符串 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.
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.
返回
true
if this string is lexically less than string
other
. Otherwise returns
false
.
This function overloads operator<().
other const char pointer is converted to a QString 使用 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.
This function overloads operator<().
other byte array is converted to a QString 使用 fromUtf8 () function. 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.
This function overloads operator<=().
other const char pointer is converted to a QString 使用 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.
This function overloads operator<=().
other byte array is converted to a QString 使用 fromUtf8 () function. If any NUL characters ('\0') are embedded in the byte array, they will be included in the transformation.
可以禁用此运算符通过定义 QT_NO_CAST_FROM_ASCII when you compile your applications. This can be useful if you want to ensure that all user-visible strings go through QObject::tr (), for example.
此函数重载 operator=()。
Sets the string to contain the single character ch .
此函数重载 operator=()。
Assigns the Latin-1 string 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.
This function overloads operator==().
other const char pointer is converted to a QString 使用 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.
This function overloads operator==().
other byte array is converted to a QString 使用 fromUtf8 () function. This function stops conversion at the first NUL character found, or the end of the byte array.
可以禁用此运算符通过定义 QT_NO_CAST_FROM_ASCII when you compile your applications. This can be useful if you want to ensure that all user-visible strings go through QObject::tr (), for example.
返回
true
if this string is lexically equal to the parameter string
other
. Otherwise returns
false
.
This function overloads operator>().
other const char pointer is converted to a QString 使用 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.
This function overloads operator>().
other byte array is converted to a QString 使用 fromUtf8 () function. If any NUL characters ('\0') are embedded in the byte array, they will be included in the transformation.
可以禁用此运算符通过定义 QT_NO_CAST_FROM_ASCII when you compile your applications. This can be useful if you want to ensure that all user-visible strings go through QObject::tr (), for example.
此函数重载运算符 >=()。
other const char pointer is converted to a QString 使用 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.
此函数重载运算符 >=()。
other byte array is converted to a QString 使用 fromUtf8 () function. If any NUL characters ('\0') are embedded in the byte array, they will be included in the transformation.
可以禁用此运算符通过定义 QT_NO_CAST_FROM_ASCII when you compile your applications. This can be useful if you want to ensure that all user-visible strings go through QObject::tr (), for example.
Returns the character at the specified position in the string as a modifiable reference.
范例:
QString str; if (str[0] == QChar('?')) str[0] = QChar('_');
另请参阅 at ().
This function overloads operator[]().
[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 .
返回
true
若字符串
s1
不等于字符串
s2
;否则返回
false
.
另请参阅 Comparing Strings .
返回
true
若字符串
s1
不等于字符串
s2
. Otherwise returns
false
.
This function overloads operator!=().
返回
true
if
s1
不等于
s2
;否则返回
false
.
For
s1
!= 0, this is equivalent to
compare(
s1
,
s2
) != 0
. Note that no string is equal to
s1
being 0.
[since 6.2]
QString
operator""_qs
(const
char16_t
*
str
,
size_t
size
)
文字运算符创建的 QString out of the first size characters in the char16_t string literal str .
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 :
auto str = u"hello"_qs;
该函数在 Qt 6.2 引入。
另请参阅 QStringLiteral and QtLiterals::operator""_qba (const char *str, size_t size).
Returns a string which is the result of concatenating s1 and s2 .
Returns a string which is the result of concatenating s1 and s2 ( s2 is converted to Unicode using the QString::fromUtf8 () 函数)。
另请参阅 QString::fromUtf8 ().
Returns a string which is the result of concatenating s1 and s2 ( s1 is converted to Unicode using the QString::fromUtf8 () 函数)。
另请参阅 QString::fromUtf8 ().
This function overloads operator<().
返回
true
若字符串
s1
词法上小于字符串
s2
;否则返回
false
.
另请参阅 Comparing Strings .
This function overloads operator<().
返回
true
if
s1
is lexically less than
s2
;否则返回
false
.
This function overloads operator<().
返回
true
if
s1
is lexically less than
s2
;否则返回
false
.
返回
true
if
s1
is lexically less than
s2
;否则返回
false
。对于
s1
!= 0, this is equivalent to
compare(s1, s2) < 0
.
另请参阅 Comparing Strings .
写入给定 string 到指定 stream .
另请参阅 序列化 Qt 数据类型 .
返回
true
若字符串
s1
词法上 <= 字符串
s2
;否则返回
false
.
另请参阅 Comparing Strings .
This function overloads operator<=().
返回
true
if
s1
is lexically less than or equal to
s2
;否则返回
false
.
This function overloads operator<=().
返回
true
if
s1
is lexically less than or equal to
s2
;否则返回
false
.
返回
true
if
s1
is lexically less than or equal to
s2
;否则返回
false
。对于
s1
!= 0, this is equivalent to
compare(s1, s2) <= 0
.
另请参阅 Comparing Strings .
This function overloads operator==().
返回
true
若字符串
s1
等于字符串
s2
;否则返回
false
.
另请参阅 Comparing Strings .
This function overloads operator==().
返回
true
if
s1
等于
s2
;否则返回
false
.
This function overloads operator==().
返回
true
if
s1
等于
s2
;否则返回
false
.
This function overloads operator==().
返回
true
if
s1
等于
s2
;否则返回
false
. Note that no string is equal to
s1
being 0.
相当于
s1 != 0 && compare(s1, s2) == 0
.
返回
true
若字符串
s1
词法上大于字符串
s2
;否则返回
false
.
另请参阅 Comparing Strings .
This function overloads operator>().
返回
true
if
s1
is lexically greater than
s2
;否则返回
false
.
This function overloads operator>().
返回
true
if
s1
is lexically greater than
s2
;否则返回
false
.
返回
true
if
s1
is lexically greater than
s2
;否则返回
false
. Equivalent to
compare(s1, s2) > 0
.
另请参阅 Comparing Strings .
返回
true
若字符串
s1
词法上大于等于字符串
s2
;否则返回
false
.
另请参阅 Comparing Strings .
此函数重载运算符 >=()。
返回
true
if
s1
is lexically greater than or equal to
s2
;否则返回
false
.
此函数重载运算符 >=()。
返回
true
if
s1
is lexically greater than or equal to
s2
;否则返回
false
.
返回
true
if
s1
is lexically greater than or equal to
s2
;否则返回
false
。对于
s1
!= 0, this is equivalent to
compare(s1, s2) >= 0
.
另请参阅 Comparing Strings .
读取字符串从指定 stream 进给定 string .
另请参阅 序列化 Qt 数据类型 .
宏生成数据为 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 实例从编译时的已知数据。
注意: QLatin1String can still be more efficient than QStringLiteral when the string is passed to a function that has an overload taking QLatin1String and this overload avoids conversion to QString . For instance, QString::operator==() can compare to a QLatin1String 直接:
if (attribute.name() == QLatin1String("http-contents-length")) //...
注意:
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 .
禁用自动转换从 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 .
禁用自动转换从
QString
到 8 位字符串 (
char *
).
另请参阅 QT_NO_CAST_FROM_ASCII , QT_RESTRICTED_CAST_FROM_ASCII ,和 QT_NO_CAST_FROM_BYTEARRAY .
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
,
QLatin1String
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 .