1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the QtCore module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
42 #include "qstringlist.h"
44 #include "qunicodetables_p.h"
45 #ifndef QT_NO_TEXTCODEC
46 #include <qtextcodec.h>
48 #include <private/qutfcodec_p.h>
50 #include <qdatastream.h>
53 #include "qlocale_p.h"
54 #include "qstringmatcher.h"
55 #include "qvarlengtharray.h"
62 #include <private/qcore_mac_p.h>
65 #include <private/qfunctions_p.h>
74 #include "qstringmatcher.cpp"
77 # include <qt_windows.h>
88 #define LLONG_MAX qint64_C(9223372036854775807)
91 #define LLONG_MIN (-LLONG_MAX - qint64_C(1))
94 #define ULLONG_MAX quint64_C(18446744073709551615)
99 #ifndef QT_NO_TEXTCODEC
100 QTextCodec *QString::codecForCStrings;
105 extern bool qt_ucol_strcoll(const QChar *source, int sourceLength, const QChar *target, int targetLength, int *result);
110 int qFindString(const QChar *haystack, int haystackLen, int from,
111 const QChar *needle, int needleLen, Qt::CaseSensitivity cs);
112 int qFindStringBoyerMoore(const QChar *haystack, int haystackLen, int from,
113 const QChar *needle, int needleLen, Qt::CaseSensitivity cs);
114 static inline int qt_last_index_of(const QChar *haystack, int haystackLen, QChar needle,
115 int from, Qt::CaseSensitivity cs);
116 static inline int qt_string_count(const QChar *haystack, int haystackLen,
117 const QChar *needle, int needleLen,
118 Qt::CaseSensitivity cs);
119 static inline int qt_string_count(const QChar *haystack, int haystackLen,
120 QChar needle, Qt::CaseSensitivity cs);
121 static inline int qt_find_latin1_string(const QChar *hay, int size, const QLatin1String &needle,
122 int from, Qt::CaseSensitivity cs);
123 static inline bool qt_starts_with(const QChar *haystack, int haystackLen,
124 const QChar *needle, int needleLen, Qt::CaseSensitivity cs);
125 static inline bool qt_starts_with(const QChar *haystack, int haystackLen,
126 const QLatin1String &needle, Qt::CaseSensitivity cs);
127 static inline bool qt_ends_with(const QChar *haystack, int haystackLen,
128 const QChar *needle, int needleLen, Qt::CaseSensitivity cs);
129 static inline bool qt_ends_with(const QChar *haystack, int haystackLen,
130 const QLatin1String &needle, Qt::CaseSensitivity cs);
132 // Unicode case-insensitive comparison
133 static int ucstricmp(const ushort *a, const ushort *ae, const ushort *b, const ushort *be)
142 const ushort *e = ae;
149 // qDebug() << hex << alast << blast;
150 // qDebug() << hex << "*a=" << *a << "alast=" << alast << "folded=" << foldCase (*a, alast);
151 // qDebug() << hex << "*b=" << *b << "blast=" << blast << "folded=" << foldCase (*b, blast);
152 int diff = foldCase(*a, alast) - foldCase(*b, blast);
166 // Case-insensitive comparison between a Unicode string and a QLatin1String
167 static int ucstricmp(const ushort *a, const ushort *ae, const uchar *b, const uchar *be)
177 const ushort *e = ae;
182 int diff = foldCase(*a) - foldCase(*b);
196 // Unicode case-sensitive compare two same-sized strings
197 static int ucstrncmp(const QChar *a, const QChar *b, int l)
199 while (l-- && *a == *b)
203 return a->unicode() - b->unicode();
206 // Unicode case-sensitive comparison
207 static int ucstrcmp(const QChar *a, int alen, const QChar *b, int blen)
209 if (a == b && alen == blen)
211 int l = qMin(alen, blen);
212 int cmp = ucstrncmp(a, b, l);
213 return cmp ? cmp : (alen-blen);
216 // Unicode case-insensitive compare two same-sized strings
217 static int ucstrnicmp(const ushort *a, const ushort *b, int l)
219 return ucstricmp(a, a + l, b, b + l);
222 // Benchmarking indicates that doing memcmp is much slower than
223 // executing the comparison ourselves.
225 // The profiling was done on a population of calls to qMemEquals, generated
226 // during a run of the demo browser. The profile of the data (32-bit x86
229 // total number of comparisons: 21353
230 // longest string compared: 95
231 // average comparison length: 14.8786
232 // cache-line crosses: 5661 (13.3%)
233 // alignment histogram:
234 // 0xXXX0 = 512 (1.2%) strings, 0 (0.0%) of which same-aligned
235 // 0xXXX2 = 15087 (35.3%) strings, 5145 (34.1%) of which same-aligned
236 // 0xXXX4 = 525 (1.2%) strings, 0 (0.0%) of which same-aligned
237 // 0xXXX6 = 557 (1.3%) strings, 6 (1.1%) of which same-aligned
238 // 0xXXX8 = 509 (1.2%) strings, 0 (0.0%) of which same-aligned
239 // 0xXXXa = 24358 (57.0%) strings, 9901 (40.6%) of which same-aligned
240 // 0xXXXc = 557 (1.3%) strings, 0 (0.0%) of which same-aligned
241 // 0xXXXe = 601 (1.4%) strings, 15 (2.5%) of which same-aligned
242 // total = 42706 (100%) strings, 15067 (35.3%) of which same-aligned
244 // 92% of the strings have alignment of 2 or 10, which is due to malloc on
245 // 32-bit Linux returning values aligned to 8 bytes, and offsetof(array, QString::Data) == 18.
247 // The profile on 64-bit will be different since offsetof(array, QString::Data) == 26.
249 // The benchmark results were, for a Core-i7 @ 2.67 GHz 32-bit, compiled with -O3 -funroll-loops:
250 // 16-bit loads only: 872,301 CPU ticks [Qt 4.5 / memcmp]
251 // 32- and 16-bit loads: 773,362 CPU ticks [Qt 4.6]
252 // SSE2 "movdqu" 128-bit loads: 618,736 CPU ticks
253 // SSE3 "lddqu" 128-bit loads: 619,954 CPU ticks
254 // SSSE3 "palignr" corrections: 852,147 CPU ticks
255 // SSE4.2 "pcmpestrm": 738,702 CPU ticks
257 // The same benchmark on an Atom N450 @ 1.66 GHz, is:
258 // 16-bit loads only: 2,185,882 CPU ticks
259 // 32- and 16-bit loads: 1,805,060 CPU ticks
260 // SSE2 "movdqu" 128-bit loads: 2,529,843 CPU ticks
261 // SSE3 "lddqu" 128-bit loads: 2,514,858 CPU ticks
262 // SSSE3 "palignr" corrections: 2,160,325 CPU ticks
263 // SSE4.2 not available
265 // The conclusion we reach is that alignment the SSE2 unaligned code can gain
266 // 20% improvement in performance in some systems, but suffers a penalty due
267 // to the unaligned loads on others.
269 static bool qMemEquals(const quint16 *a, const quint16 *b, int length)
271 if (a == b || !length)
283 if ((sa.value & 2) == (sb.value & 2)) {
284 // both addresses have the same alignment
286 // both addresses are not aligned to 4-bytes boundaries
287 // compare the first character
294 // now both addresses are 4-bytes aligned
297 // both addresses are 4-bytes aligned
298 // do a fast 32-bit comparison
299 register const quint32 *e = sa.d + (length >> 1);
300 for ( ; sa.d != e; ++sa.d, ++sb.d) {
305 // do we have a tail?
306 return (length & 1) ? *sa.w == *sb.w : true;
308 // one of the addresses isn't 4-byte aligned but the other is
309 register const quint16 *e = sa.w + length;
310 for ( ; sa.w != e; ++sa.w, ++sb.w) {
321 Returns the index position of the first occurrence of the
322 character \a ch in the string given by \a str and \a len,
323 searching forward from index
324 position \a from. Returns -1 if \a ch could not be found.
326 static int findChar(const QChar *str, int len, QChar ch, int from,
327 Qt::CaseSensitivity cs)
329 const ushort *s = (const ushort *)str;
330 ushort c = ch.unicode();
332 from = qMax(from + len, 0);
334 const ushort *n = s + from - 1;
335 const ushort *e = s + len;
336 if (cs == Qt::CaseSensitive) {
343 if (foldCase(*n) == c)
351 if (sl_minus_1 < (int)sizeof(int) * CHAR_BIT) \
352 hashHaystack -= (a) << sl_minus_1; \
355 inline bool qIsUpper(char ch)
357 return ch >= 'A' && ch <= 'Z';
360 inline bool qIsDigit(char ch)
362 return ch >= '0' && ch <= '9';
365 inline char qToLower(char ch)
367 if (ch >= 'A' && ch <= 'Z')
368 return ch - 'A' + 'a';
373 const QString::Null QString::null = { };
376 \macro QT_NO_CAST_FROM_ASCII
379 Disables automatic conversions from 8-bit strings (char *) to unicode QStrings
381 \sa QT_NO_CAST_TO_ASCII, QT_NO_CAST_FROM_BYTEARRAY
385 \macro QT_NO_CAST_TO_ASCII
388 disables automatic conversion from QString to 8-bit strings (char *)
390 \sa QT_NO_CAST_FROM_ASCII, QT_NO_CAST_FROM_BYTEARRAY
394 \macro QT_ASCII_CAST_WARNINGS
398 This macro can be defined to force a warning whenever a function is
399 called that automatically converts between unicode and 8-bit encodings.
401 Note: This only works for compilers that support warnings for
404 \sa QT_NO_CAST_TO_ASCII, QT_NO_CAST_FROM_ASCII
410 \brief The QCharRef class is a helper class for QString.
414 \ingroup string-processing
416 When you get an object of type QCharRef, if you can assign to it,
417 the assignment will apply to the character in the string from
418 which you got the reference. That is its whole purpose in life.
419 The QCharRef becomes invalid once modifications are made to the
420 string: if you want to keep the character, copy it into a QChar.
422 Most of the QChar member functions also exist in QCharRef.
423 However, they are not explicitly documented here.
425 \sa QString::operator[]() QString::at() QChar
432 \brief The QString class provides a Unicode character string.
436 \ingroup string-processing
438 QString stores a string of 16-bit \l{QChar}s, where each QChar
439 corresponds one Unicode 4.0 character. (Unicode characters
440 with code values above 65535 are stored using surrogate pairs,
441 i.e., two consecutive \l{QChar}s.)
443 \l{Unicode} is an international standard that supports most of the
444 writing systems in use today. It is a superset of US-ASCII (ANSI
445 X3.4-1986) and Latin-1 (ISO 8859-1), and all the US-ASCII/Latin-1
446 characters are available at the same code positions.
448 Behind the scenes, QString uses \l{implicit sharing}
449 (copy-on-write) to reduce memory usage and to avoid the needless
450 copying of data. This also helps reduce the inherent overhead of
451 storing 16-bit characters instead of 8-bit characters.
453 In addition to QString, Qt also provides the QByteArray class to
454 store raw bytes and traditional 8-bit '\\0'-terminated strings.
455 For most purposes, QString is the class you want to use. It is
456 used throughout the Qt API, and the Unicode support ensures that
457 your applications will be easy to translate if you want to expand
458 your application's market at some point. The two main cases where
459 QByteArray is appropriate are when you need to store raw binary
460 data, and when memory conservation is critical (e.g., with
461 \l{Qt for Embedded Linux}).
465 \section1 Initializing a String
467 One way to initialize a QString is simply to pass a \c{const char
468 *} to its constructor. For example, the following code creates a
469 QString of size 5 containing the data "Hello":
471 \snippet doc/src/snippets/qstring/main.cpp 0
473 QString converts the \c{const char *} data into Unicode using the
474 fromAscii() function. By default, fromAscii() treats character
475 above 128 as Latin-1 characters, but this can be changed by
476 calling QTextCodec::setCodecForCStrings().
478 In all of the QString functions that take \c{const char *}
479 parameters, the \c{const char *} is interpreted as a classic
480 C-style '\\0'-terminated string. It is legal for the \c{const char
481 *} parameter to be 0.
483 You can also provide string data as an array of \l{QChar}s:
485 \snippet doc/src/snippets/qstring/main.cpp 1
487 QString makes a deep copy of the QChar data, so you can modify it
488 later without experiencing side effects. (If for performance
489 reasons you don't want to take a deep copy of the character data,
490 use QString::fromRawData() instead.)
492 Another approach is to set the size of the string using resize()
493 and to initialize the data character per character. QString uses
494 0-based indexes, just like C++ arrays. To access the character at
495 a particular index position, you can use \l operator[](). On
496 non-const strings, \l operator[]() returns a reference to a
497 character that can be used on the left side of an assignment. For
500 \snippet doc/src/snippets/qstring/main.cpp 2
502 For read-only access, an alternative syntax is to use the at()
505 \snippet doc/src/snippets/qstring/main.cpp 3
507 The at() function can be faster than \l operator[](), because it
508 never causes a \l{deep copy} to occur. Alternatively, use the
509 left(), right(), or mid() functions to extract several characters
512 A QString can embed '\\0' characters (QChar::Null). The size()
513 function always returns the size of the whole string, including
514 embedded '\\0' characters.
516 After a call to the resize() function, newly allocated characters
517 have undefined values. To set all the characters in the string to
518 a particular value, use the fill() function.
520 QString provides dozens of overloads designed to simplify string
521 usage. For example, if you want to compare a QString with a string
522 literal, you can write code like this and it will work as expected:
524 \snippet doc/src/snippets/qstring/main.cpp 4
526 You can also pass string literals to functions that take QStrings
527 as arguments, invoking the QString(const char *)
528 constructor. Similarly, you can pass a QString to a function that
529 takes a \c{const char *} argument using the \l qPrintable() macro
530 which returns the given QString as a \c{const char *}. This is
531 equivalent to calling <QString>.toLocal8Bit().constData().
533 \section1 Manipulating String Data
535 QString provides the following basic functions for modifying the
536 character data: append(), prepend(), insert(), replace(), and
537 remove(). For example:
539 \snippet doc/src/snippets/qstring/main.cpp 5
541 If you are building a QString gradually and know in advance
542 approximately how many characters the QString will contain, you
543 can call reserve(), asking QString to preallocate a certain amount
544 of memory. You can also call capacity() to find out how much
545 memory QString actually allocated.
547 The replace() and remove() functions' first two arguments are the
548 position from which to start erasing and the number of characters
549 that should be erased. If you want to replace all occurrences of
550 a particular substring with another, use one of the two-parameter
553 A frequent requirement is to remove whitespace characters from a
554 string ('\\n', '\\t', ' ', etc.). If you want to remove whitespace
555 from both ends of a QString, use the trimmed() function. If you
556 want to remove whitespace from both ends and replace multiple
557 consecutive whitespaces with a single space character within the
558 string, use simplified().
560 If you want to find all occurrences of a particular character or
561 substring in a QString, use the indexOf() or lastIndexOf()
562 functions. The former searches forward starting from a given index
563 position, the latter searches backward. Both return the index
564 position of the character or substring if they find it; otherwise,
565 they return -1. For example, here's a typical loop that finds all
566 occurrences of a particular substring:
568 \snippet doc/src/snippets/qstring/main.cpp 6
570 QString provides many functions for converting numbers into
571 strings and strings into numbers. See the arg() functions, the
572 setNum() functions, the number() static functions, and the
573 toInt(), toDouble(), and similar functions.
575 To get an upper- or lowercase version of a string use toUpper() or
578 Lists of strings are handled by the QStringList class. You can
579 split a string into a list of strings using the split() function,
580 and join a list of strings into a single string with an optional
581 separator using QStringList::join(). You can obtain a list of
582 strings from a string list that contain a particular substring or
583 that match a particular QRegExp using the QStringList::filter()
586 \section1 Querying String Data
588 If you want to see if a QString starts or ends with a particular
589 substring use startsWith() or endsWith(). If you simply want to
590 check whether a QString contains a particular character or
591 substring, use the contains() function. If you want to find out
592 how many times a particular character or substring occurs in the
595 QStrings can be compared using overloaded operators such as \l
596 operator<(), \l operator<=(), \l operator==(), \l operator>=(),
597 and so on. Note that the comparison is based exclusively on the
598 numeric Unicode values of the characters. It is very fast, but is
599 not what a human would expect; the QString::localeAwareCompare()
600 function is a better choice for sorting user-interface strings.
602 To obtain a pointer to the actual character data, call data() or
603 constData(). These functions return a pointer to the beginning of
604 the QChar data. The pointer is guaranteed to remain valid until a
605 non-const function is called on the QString.
607 \section1 Converting Between 8-Bit Strings and Unicode Strings
609 QString provides the following four functions that return a
610 \c{const char *} version of the string as QByteArray: toAscii(),
611 toLatin1(), toUtf8(), and toLocal8Bit().
614 \o toAscii() returns an 8-bit string encoded using the codec
615 specified by QTextCodec::codecForCStrings (by default, that is
617 \o toLatin1() returns a Latin-1 (ISO 8859-1) encoded 8-bit string.
618 \o toUtf8() returns a UTF-8 encoded 8-bit string. UTF-8 is a
619 superset of US-ASCII (ANSI X3.4-1986) that supports the entire
620 Unicode character set through multibyte sequences.
621 \o toLocal8Bit() returns an 8-bit string using the system's local
625 To convert from one of these encodings, QString provides
626 fromAscii(), fromLatin1(), fromUtf8(), and fromLocal8Bit(). Other
627 encodings are supported through the QTextCodec class.
629 As mentioned above, QString provides a lot of functions and
630 operators that make it easy to interoperate with \c{const char *}
631 strings. But this functionality is a double-edged sword: It makes
632 QString more convenient to use if all strings are US-ASCII or
633 Latin-1, but there is always the risk that an implicit conversion
634 from or to \c{const char *} is done using the wrong 8-bit
635 encoding. To minimize these risks, you can turn off these implicit
636 conversions by defining the following two preprocessor symbols:
639 \o \c QT_NO_CAST_FROM_ASCII disables automatic conversions from
640 C string literals and pointers to Unicode.
641 \o \c QT_NO_CAST_TO_ASCII disables automatic conversion from QString
645 One way to define these preprocessor symbols globally for your
646 application is to add the following entry to your
647 \l{qmake Project Files}{qmake project file}:
649 \snippet doc/src/snippets/code/src_corelib_tools_qstring.cpp 0
651 You then need to explicitly call fromAscii(), fromLatin1(),
652 fromUtf8(), or fromLocal8Bit() to construct a QString from an
653 8-bit string, or use the lightweight QLatin1String class, for
656 \snippet doc/src/snippets/code/src_corelib_tools_qstring.cpp 1
658 Similarly, you must call toAscii(), toLatin1(), toUtf8(), or
659 toLocal8Bit() explicitly to convert the QString to an 8-bit
660 string. (Other encodings are supported through the QTextCodec
665 \o Note for C Programmers
669 Due to C++'s type system and the fact that QString is
670 \l{implicitly shared}, QStrings may be treated like \c{int}s or
671 other basic types. For example:
673 \snippet doc/src/snippets/qstring/main.cpp 7
675 The \c result variable, is a normal variable allocated on the
676 stack. When \c return is called, and because we're returning by
677 value, the copy constructor is called and a copy of the string is
678 returned. No actual copying takes place thanks to the implicit
683 \section1 Distinction Between Null and Empty Strings
685 For historical reasons, QString distinguishes between a null
686 string and an empty string. A \e null string is a string that is
687 initialized using QString's default constructor or by passing
688 (const char *)0 to the constructor. An \e empty string is any
689 string with size 0. A null string is always empty, but an empty
690 string isn't necessarily null:
692 \snippet doc/src/snippets/qstring/main.cpp 8
694 All functions except isNull() treat null strings the same as empty
695 strings. For example, toAscii().constData() returns a pointer to a
696 '\\0' character for a null string (\e not a null pointer), and
697 QString() compares equal to QString(""). We recommend that you
698 always use the isEmpty() function and avoid isNull().
700 \section1 Argument Formats
702 In member functions where an argument \e format can be specified
703 (e.g., arg(), number()), the argument \e format can be one of the
707 \header \o Format \o Meaning
708 \row \o \c e \o format as [-]9.9e[+|-]999
709 \row \o \c E \o format as [-]9.9E[+|-]999
710 \row \o \c f \o format as [-]9.9
711 \row \o \c g \o use \c e or \c f format, whichever is the most concise
712 \row \o \c G \o use \c E or \c f format, whichever is the most concise
715 A \e precision is also specified with the argument \e format. For
716 the 'e', 'E', and 'f' formats, the \e precision represents the
717 number of digits \e after the decimal point. For the 'g' and 'G'
718 formats, the \e precision represents the maximum number of
719 significant digits (trailing zeroes are omitted).
721 \section1 More Efficient String Construction
723 Many strings are known at compile time. But the trivial
724 constructor QString("Hello"), will convert the string literal
725 to a QString using the codecForCStrings(). To avoid this one
726 can use the QStringLiteral macro to directly create the required
727 data at compile time. Constructing a QString out of the literal
728 does then not cause any overhead at runtime.
730 A slightly less efficient way is to use QLatin1String. This class wraps
731 a C string literal, precalculates it length at compile time and can
732 then be used for faster comparison with QStrings and conversion to
733 QStrings than a regular C string literal.
735 Using the QString \c{'+'} operator, it is easy to construct a
736 complex string from multiple substrings. You will often write code
739 \snippet doc/src/snippets/qstring/stringbuilder.cpp 0
741 There is nothing wrong with either of these string constructions,
742 but there are a few hidden inefficiencies. Beginning with Qt 4.6,
743 you can eliminate them.
745 First, multiple uses of the \c{'+'} operator usually means
746 multiple memory allocations. When concatenating \e{n} substrings,
747 where \e{n > 2}, there can be as many as \e{n - 1} calls to the
750 In 4.6, an internal template class \c{QStringBuilder} has been
751 added along with a few helper functions. This class is marked
752 internal and does not appear in the documentation, because you
753 aren't meant to instantiate it in your code. Its use will be
754 automatic, as described below. The class is found in
755 \c {src/corelib/tools/qstringbuilder.cpp} if you want to have a
758 \c{QStringBuilder} uses expression templates and reimplements the
759 \c{'%'} operator so that when you use \c{'%'} for string
760 concatenation instead of \c{'+'}, multiple substring
761 concatenations will be postponed until the final result is about
762 to be assigned to a QString. At this point, the amount of memory
763 required for the final result is known. The memory allocator is
764 then called \e{once} to get the required space, and the substrings
765 are copied into it one by one.
767 Additional efficiency is gained by inlining and reduced reference
768 counting (the QString created from a \c{QStringBuilder} typically
769 has a ref count of 1, whereas QString::append() needs an extra
772 There are three ways you can access this improved method of string
773 construction. The straightforward way is to include
774 \c{QStringBuilder} wherever you want to use it, and use the
775 \c{'%'} operator instead of \c{'+'} when concatenating strings:
777 \snippet doc/src/snippets/qstring/stringbuilder.cpp 5
779 A more global approach which is the most convenient but
780 not entirely source compatible, is to this define in your
783 \snippet doc/src/snippets/qstring/stringbuilder.cpp 3
785 and the \c{'+'} will automatically be performed as the
786 \c{QStringBuilder} \c{'%'} everywhere.
788 \sa fromRawData(), QChar, QLatin1String, QByteArray, QStringRef
792 \enum QString::SplitBehavior
794 This enum specifies how the split() function should behave with
795 respect to empty strings.
797 \value KeepEmptyParts If a field is empty, keep it in the result.
798 \value SkipEmptyParts If a field is empty, don't include it in the result.
803 const QConstStringData<1> QString::shared_null = { { Q_REFCOUNT_INITIALIZER(-1), 0, 0, false, { 0 } }, { 0 } };
804 const QConstStringData<1> QString::shared_empty = { { Q_REFCOUNT_INITIALIZER(-1), 0, 0, false, { 0 } }, { 0 } };
806 int QString::grow(int size)
808 return qAllocMore(size * sizeof(QChar), sizeof(Data)) / sizeof(QChar);
811 /*! \typedef QString::ConstIterator
813 Qt-style synonym for QString::const_iterator.
816 /*! \typedef QString::Iterator
818 Qt-style synonym for QString::iterator.
821 /*! \typedef QString::const_iterator
823 The QString::const_iterator typedef provides an STL-style const
824 iterator for QString.
826 \sa QString::iterator
829 /*! \typedef QString::iterator
831 The QString::iterator typedef provides an STL-style non-const
832 iterator for QString.
834 \sa QString::const_iterator
838 \typedef QString::const_reference
840 The QString::const_reference typedef provides an STL-style
841 const reference for QString.
844 \typedef QString::reference
846 The QString::const_reference typedef provides an STL-style
847 reference for QString.
850 \typedef QString::value_type
852 The QString::const_reference typedef provides an STL-style
853 value type for QString.
856 /*! \fn QString::iterator QString::begin()
858 Returns an \l{STL-style iterator} pointing to the first character in
861 \sa constBegin(), end()
864 /*! \fn QString::const_iterator QString::begin() const
869 /*! \fn QString::const_iterator QString::constBegin() const
871 Returns a const \l{STL-style iterator} pointing to the first character
874 \sa begin(), constEnd()
877 /*! \fn QString::iterator QString::end()
879 Returns an \l{STL-style iterator} pointing to the imaginary character
880 after the last character in the string.
882 \sa begin(), constEnd()
885 /*! \fn QString::const_iterator QString::end() const
890 /*! \fn QString::const_iterator QString::constEnd() const
892 Returns a const \l{STL-style iterator} pointing to the imaginary
893 item after the last item in the list.
895 \sa constBegin(), end()
899 \fn QString::QString()
901 Constructs a null string. Null strings are also empty.
906 /*! \fn QString::QString(const char *str)
908 Constructs a string initialized with the 8-bit string \a str. The
909 given const char pointer is converted to Unicode using the
910 fromAscii() function.
912 You can disable this constructor by defining \c
913 QT_NO_CAST_FROM_ASCII when you compile your applications. This
914 can be useful if you want to ensure that all user-visible strings
915 go through QObject::tr(), for example.
917 \sa fromAscii(), fromLatin1(), fromLocal8Bit(), fromUtf8()
920 /*! \fn QString QString::fromStdString(const std::string &str)
922 Returns a copy of the \a str string. The given string is converted
923 to Unicode using the fromAscii() function.
925 This constructor is only available if Qt is configured with STL
926 compatibility enabled.
928 \sa fromAscii(), fromLatin1(), fromLocal8Bit(), fromUtf8()
931 /*! \fn QString QString::fromStdWString(const std::wstring &str)
933 Returns a copy of the \a str string. The given string is assumed
934 to be encoded in utf16 if the size of wchar_t is 2 bytes (e.g. on
935 windows) and ucs4 if the size of wchar_t is 4 bytes (most Unix
938 This method is only available if Qt is configured with STL
939 compatibility enabled and if QT_NO_STL is not defined.
941 \sa fromUtf16(), fromLatin1(), fromLocal8Bit(), fromUtf8(), fromUcs4()
944 /*! \fn QString QString::fromWCharArray(const wchar_t *string, int size)
947 Returns a copy of the \a string, where the encoding of \a string depends on
948 the size of wchar. If wchar is 4 bytes, the \a string is interpreted as ucs-4,
949 if wchar is 2 bytes it is interpreted as ucs-2.
951 If \a size is -1 (default), the \a string has to be 0 terminated.
953 \sa fromUtf16(), fromLatin1(), fromLocal8Bit(), fromUtf8(), fromUcs4(), fromStdWString()
956 /*! \fn std::wstring QString::toStdWString() const
958 Returns a std::wstring object with the data contained in this
959 QString. The std::wstring is encoded in utf16 on platforms where
960 wchar_t is 2 bytes wide (e.g. windows) and in ucs4 on platforms
961 where wchar_t is 4 bytes wide (most Unix systems).
963 This operator is mostly useful to pass a QString to a function
964 that accepts a std::wstring object.
966 This operator is only available if Qt is configured with STL
967 compatibility enabled and if QT_NO_STL is not defined.
969 \sa utf16(), toAscii(), toLatin1(), toUtf8(), toLocal8Bit()
972 // ### replace with QCharIterator
973 int QString::toUcs4_helper(const ushort *uc, int length, uint *out)
976 for (; i < length; ++i) {
978 if (QChar::isHighSurrogate(u) && i + 1 < length) {
979 ushort low = uc[i+1];
980 if (QChar::isLowSurrogate(low)) {
982 u = QChar::surrogateToUcs4(u, low);
990 /*! \fn int QString::toWCharArray(wchar_t *array) const
993 Fills the \a array with the data contained in this QString object.
994 The array is encoded in utf16 on platforms where
995 wchar_t is 2 bytes wide (e.g. windows) and in ucs4 on platforms
996 where wchar_t is 4 bytes wide (most Unix systems).
998 \a array has to be allocated by the caller and contain enough space to
999 hold the complete string (allocating the array with the same length as the
1000 string is always sufficient).
1002 returns the actual length of the string in \a array.
1004 \note This function does not append a null character to the array.
1006 \sa utf16(), toUcs4(), toAscii(), toLatin1(), toUtf8(), toLocal8Bit(), toStdWString()
1009 /*! \fn QString::QString(const QString &other)
1011 Constructs a copy of \a other.
1013 This operation takes \l{constant time}, because QString is
1014 \l{implicitly shared}. This makes returning a QString from a
1015 function very fast. If a shared instance is modified, it will be
1016 copied (copy-on-write), and that takes \l{linear time}.
1022 Constructs a string initialized with the first \a size characters
1023 of the QChar array \a unicode.
1025 QString makes a deep copy of the string data. The unicode data is copied as
1026 is and the Byte Order Mark is preserved if present.
1028 QString::QString(const QChar *unicode, int size)
1031 d = const_cast<Data *>(&shared_null.str);
1032 } else if (size <= 0) {
1033 d = const_cast<Data *>(&shared_empty.str);
1035 d = (Data*) ::malloc(sizeof(Data)+(size+1)*sizeof(QChar));
1039 d->alloc = (uint) size;
1040 d->capacityReserved = false;
1042 memcpy(d->data(), unicode, size * sizeof(QChar));
1043 d->data()[size] = '\0';
1050 Constructs a string initialized with the characters of the QChar array
1051 \a unicode, which must be terminated with a 0.
1053 QString makes a deep copy of the string data. The unicode data is copied as
1054 is and the Byte Order Mark is preserved if present.
1056 QString::QString(const QChar *unicode)
1059 d = const_cast<Data *>(&shared_null.str);
1062 while (unicode[size] != 0)
1065 d = const_cast<Data *>(&shared_empty.str);
1067 d = (Data*) ::malloc(sizeof(Data)+(size+1)*sizeof(QChar));
1071 d->alloc = (uint) size;
1072 d->capacityReserved = false;
1074 memcpy(d->data(), unicode, size * sizeof(QChar));
1075 d->data()[size] = '\0';
1082 Constructs a string of the given \a size with every character set
1087 QString::QString(int size, QChar ch)
1090 d = const_cast<Data *>(&shared_empty.str);
1092 d = (Data*) ::malloc(sizeof(Data)+(size+1)*sizeof(QChar));
1096 d->alloc = (uint) size;
1097 d->capacityReserved = false;
1099 d->data()[size] = '\0';
1100 ushort *i = d->data() + size;
1101 ushort *b = d->data();
1102 const ushort value = ch.unicode();
1108 /*! \fn QString::QString(int size, Qt::Initialization)
1111 Constructs a string of the given \a size without initializing the
1112 characters. This is only used in \c QStringBuilder::toString().
1114 QString::QString(int size, Qt::Initialization)
1116 d = (Data*) ::malloc(sizeof(Data)+(size+1)*sizeof(QChar));
1120 d->alloc = (uint) size;
1121 d->capacityReserved = false;
1123 d->data()[size] = '\0';
1126 /*! \fn QString::QString(const QLatin1String &str)
1128 Constructs a copy of the Latin-1 string \a str.
1134 Constructs a string of size 1 containing the character \a ch.
1136 QString::QString(QChar ch)
1138 d = (Data *) ::malloc(sizeof(Data) + 2*sizeof(QChar));
1143 d->capacityReserved = false;
1145 d->data()[0] = ch.unicode();
1146 d->data()[1] = '\0';
1149 /*! \fn QString::QString(const QByteArray &ba)
1151 Constructs a string initialized with the byte array \a ba. The
1152 given byte array is converted to Unicode using fromAscii(). Stops
1153 copying at the first 0 character, otherwise copies the entire byte
1156 You can disable this constructor by defining \c
1157 QT_NO_CAST_FROM_ASCII when you compile your applications. This
1158 can be useful if you want to ensure that all user-visible strings
1159 go through QObject::tr(), for example.
1161 \sa fromAscii(), fromLatin1(), fromLocal8Bit(), fromUtf8()
1164 /*! \fn QString::QString(const Null &)
1168 /*! \fn QString &QString::operator=(const Null &)
1173 \fn QString::~QString()
1175 Destroys the string.
1179 /*! \fn void QString::swap(QString &other)
1182 Swaps string \a other with this string. This operation is very fast and
1186 /*! \fn void QString::detach()
1191 /*! \fn bool QString::isDetached() const
1196 /*! \fn bool QString::isSharedWith(const QString &other) const
1201 // ### Qt 5: rename freeData() to avoid confusion. See task 197625.
1202 void QString::free(Data *d)
1208 Sets the size of the string to \a size characters.
1210 If \a size is greater than the current size, the string is
1211 extended to make it \a size characters long with the extra
1212 characters added to the end. The new characters are uninitialized.
1214 If \a size is less than the current size, characters are removed
1219 \snippet doc/src/snippets/qstring/main.cpp 45
1221 If you want to append a certain number of identical characters to
1222 the string, use \l operator+=() as follows rather than resize():
1224 \snippet doc/src/snippets/qstring/main.cpp 46
1226 If you want to expand the string so that it reaches a certain
1227 width and fill the new positions with a particular character, use
1228 the leftJustified() function:
1230 If \a size is negative, it is equivalent to passing zero.
1232 \snippet doc/src/snippets/qstring/main.cpp 47
1234 \sa truncate(), reserve()
1237 void QString::resize(int size)
1242 if (d->offset && d->ref == 1 && size < d->size) {
1247 if (size == 0 && !d->capacityReserved) {
1248 Data *x = const_cast<Data *>(&shared_empty.str);
1249 if (!d->ref.deref())
1253 if (d->ref != 1 || size > int(d->alloc) ||
1254 (!d->capacityReserved && size < d->size && size < int(d->alloc) >> 1))
1255 realloc(grow(size));
1256 if (int(d->alloc) >= size) {
1258 d->data()[size] = '\0';
1263 /*! \fn int QString::capacity() const
1265 Returns the maximum number of characters that can be stored in
1266 the string without forcing a reallocation.
1268 The sole purpose of this function is to provide a means of fine
1269 tuning QString's memory usage. In general, you will rarely ever
1270 need to call this function. If you want to know how many
1271 characters are in the string, call size().
1273 \sa reserve(), squeeze()
1277 \fn void QString::reserve(int size)
1279 Attempts to allocate memory for at least \a size characters. If
1280 you know in advance how large the string will be, you can call
1281 this function, and if you resize the string often you are likely
1282 to get better performance. If \a size is an underestimate, the
1283 worst that will happen is that the QString will be a bit slower.
1285 The sole purpose of this function is to provide a means of fine
1286 tuning QString's memory usage. In general, you will rarely ever
1287 need to call this function. If you want to change the size of the
1288 string, call resize().
1290 This function is useful for code that needs to build up a long
1291 string and wants to avoid repeated reallocation. In this example,
1292 we want to add to the string until some condition is true, and
1293 we're fairly sure that size is large enough to make a call to
1294 reserve() worthwhile:
1296 \snippet doc/src/snippets/qstring/main.cpp 44
1298 \sa squeeze(), capacity()
1302 \fn void QString::squeeze()
1304 Releases any memory not required to store the character data.
1306 The sole purpose of this function is to provide a means of fine
1307 tuning QString's memory usage. In general, you will rarely ever
1308 need to call this function.
1310 \sa reserve(), capacity()
1313 // ### Qt 5: rename reallocData() to avoid confusion. 197625
1314 void QString::realloc(int alloc)
1316 if (d->ref != 1 || d->offset) {
1317 Data *x = static_cast<Data *>(::malloc(sizeof(Data) + (alloc+1) * sizeof(QChar)));
1320 x->size = qMin(alloc, d->size);
1321 x->alloc = (uint) alloc;
1322 x->capacityReserved = d->capacityReserved;
1324 ::memcpy(x->data(), d->data(), x->size * sizeof(QChar));
1325 x->data()[x->size] = 0;
1326 if (!d->ref.deref())
1330 Data *p = static_cast<Data *>(::realloc(d, sizeof(Data) + (alloc+1) * sizeof(QChar)));
1338 void QString::realloc()
1343 void QString::expand(int i)
1346 resize(qMax(i + 1, sz));
1347 if (d->size - 1 > sz) {
1348 ushort *n = d->data() + d->size - 1;
1349 ushort *e = d->data() + sz;
1355 /*! \fn void QString::clear()
1357 Clears the contents of the string and makes it empty.
1359 \sa resize(), isEmpty()
1362 /*! \fn QString &QString::operator=(const QString &other)
1364 Assigns \a other to this string and returns a reference to this
1368 QString &QString::operator=(const QString &other)
1371 if (!d->ref.deref())
1378 /*! \fn QString &QString::operator=(const QLatin1String &str)
1380 \overload operator=()
1382 Assigns the Latin-1 string \a str to this string.
1385 /*! \fn QString &QString::operator=(const QByteArray &ba)
1387 \overload operator=()
1389 Assigns \a ba to this string. The byte array is converted to Unicode
1390 using the fromAscii() function. This function stops conversion at the
1391 first NUL character found, or the end of the \a ba byte array.
1393 You can disable this operator by defining \c
1394 QT_NO_CAST_FROM_ASCII when you compile your applications. This
1395 can be useful if you want to ensure that all user-visible strings
1396 go through QObject::tr(), for example.
1399 /*! \fn QString &QString::operator=(const char *str)
1401 \overload operator=()
1403 Assigns \a str to this string. The const char pointer is converted
1404 to Unicode using the fromAscii() function.
1406 You can disable this operator by defining \c
1407 QT_NO_CAST_FROM_ASCII when you compile your applications. This
1408 can be useful if you want to ensure that all user-visible strings
1409 go through QObject::tr(), for example.
1412 /*! \fn QString &QString::operator=(char ch)
1414 \overload operator=()
1416 Assigns character \a ch to this string. The character is converted
1417 to Unicode using the fromAscii() function.
1419 You can disable this operator by defining \c
1420 QT_NO_CAST_FROM_ASCII when you compile your applications. This
1421 can be useful if you want to ensure that all user-visible strings
1422 go through QObject::tr(), for example.
1426 \overload operator=()
1428 Sets the string to contain the single character \a ch.
1430 QString &QString::operator=(QChar ch)
1432 return operator=(QString(ch));
1436 \fn QString& QString::insert(int position, const QString &str)
1438 Inserts the string \a str at the given index \a position and
1439 returns a reference to this string.
1443 \snippet doc/src/snippets/qstring/main.cpp 26
1445 If the given \a position is greater than size(), the array is
1446 first extended using resize().
1448 \sa append(), prepend(), replace(), remove()
1453 \fn QString &QString::insert(int position, const QLatin1String &str)
1456 Inserts the Latin-1 string \a str at the given index \a position.
1458 QString &QString::insert(int i, const QLatin1String &str)
1460 const uchar *s = (const uchar *)str.latin1();
1461 if (i < 0 || !s || !(*s))
1464 int len = str.size();
1465 expand(qMax(d->size, i) + len - 1);
1467 ::memmove(d->data() + i + len, d->data() + i, (d->size - i - len) * sizeof(QChar));
1468 for (int j = 0; j < len; ++j)
1469 d->data()[i + j] = s[j];
1474 \fn QString& QString::insert(int position, const QChar *unicode, int size)
1477 Inserts the first \a size characters of the QChar array \a unicode
1478 at the given index \a position in the string.
1480 QString& QString::insert(int i, const QChar *unicode, int size)
1482 if (i < 0 || size <= 0)
1485 const ushort *s = (const ushort *)unicode;
1486 if (s >= d->data() && s < d->data() + d->alloc) {
1487 // Part of me - take a copy
1488 ushort *tmp = static_cast<ushort *>(::malloc(size * sizeof(QChar)));
1490 memcpy(tmp, s, size * sizeof(QChar));
1491 insert(i, reinterpret_cast<const QChar *>(tmp), size);
1496 expand(qMax(d->size, i) + size - 1);
1498 ::memmove(d->data() + i + size, d->data() + i, (d->size - i - size) * sizeof(QChar));
1499 memcpy(d->data() + i, s, size * sizeof(QChar));
1504 \fn QString& QString::insert(int position, QChar ch)
1507 Inserts \a ch at the given index \a position in the string.
1510 QString& QString::insert(int i, QChar ch)
1516 expand(qMax(i, d->size));
1517 ::memmove(d->data() + i + 1, d->data() + i, (d->size - i) * sizeof(QChar));
1518 d->data()[i] = ch.unicode();
1523 Appends the string \a str onto the end of this string.
1527 \snippet doc/src/snippets/qstring/main.cpp 9
1529 This is the same as using the insert() function:
1531 \snippet doc/src/snippets/qstring/main.cpp 10
1533 The append() function is typically very fast (\l{constant time}),
1534 because QString preallocates extra space at the end of the string
1535 data so it can grow without reallocating the entire string each
1538 \sa operator+=(), prepend(), insert()
1540 QString &QString::append(const QString &str)
1542 if (str.d != &shared_null.str) {
1543 if (d == &shared_null.str) {
1546 if (d->ref != 1 || d->size + str.d->size > int(d->alloc))
1547 realloc(grow(d->size + str.d->size));
1548 memcpy(d->data() + d->size, str.d->data(), str.d->size * sizeof(QChar));
1549 d->size += str.d->size;
1550 d->data()[d->size] = '\0';
1559 Appends the Latin-1 string \a str to this string.
1561 QString &QString::append(const QLatin1String &str)
1563 const uchar *s = (const uchar *)str.latin1();
1565 int len = str.size();
1566 if (d->ref != 1 || d->size + len > int(d->alloc))
1567 realloc(grow(d->size + len));
1568 ushort *i = d->data() + d->size;
1569 while ((*i++ = *s++))
1576 /*! \fn QString &QString::append(const QByteArray &ba)
1580 Appends the byte array \a ba to this string. The given byte array
1581 is converted to Unicode using the fromAscii() function.
1583 You can disable this function by defining \c QT_NO_CAST_FROM_ASCII
1584 when you compile your applications. This can be useful if you want
1585 to ensure that all user-visible strings go through QObject::tr(),
1589 /*! \fn QString &QString::append(const char *str)
1593 Appends the string \a str to this string. The given const char
1594 pointer is converted to Unicode using the fromAscii() function.
1596 You can disable this function by defining \c QT_NO_CAST_FROM_ASCII
1597 when you compile your applications. This can be useful if you want
1598 to ensure that all user-visible strings go through QObject::tr(),
1605 Appends the character \a ch to this string.
1607 QString &QString::append(QChar ch)
1609 if (d->ref != 1 || d->size + 1 > int(d->alloc))
1610 realloc(grow(d->size + 1));
1611 d->data()[d->size++] = ch.unicode();
1612 d->data()[d->size] = '\0';
1616 /*! \fn QString &QString::prepend(const QString &str)
1618 Prepends the string \a str to the beginning of this string and
1619 returns a reference to this string.
1623 \snippet doc/src/snippets/qstring/main.cpp 36
1625 \sa append(), insert()
1628 /*! \fn QString &QString::prepend(const QLatin1String &str)
1632 Prepends the Latin-1 string \a str to this string.
1635 /*! \fn QString &QString::prepend(const QByteArray &ba)
1639 Prepends the byte array \a ba to this string. The byte array is
1640 converted to Unicode using the fromAscii() function.
1642 You can disable this function by defining \c
1643 QT_NO_CAST_FROM_ASCII when you compile your applications. This
1644 can be useful if you want to ensure that all user-visible strings
1645 go through QObject::tr(), for example.
1648 /*! \fn QString &QString::prepend(const char *str)
1652 Prepends the string \a str to this string. The const char pointer
1653 is converted to Unicode using the fromAscii() function.
1655 You can disable this function by defining \c
1656 QT_NO_CAST_FROM_ASCII when you compile your applications. This
1657 can be useful if you want to ensure that all user-visible strings
1658 go through QObject::tr(), for example.
1661 /*! \fn QString &QString::prepend(QChar ch)
1665 Prepends the character \a ch to this string.
1669 \fn QString &QString::remove(int position, int n)
1671 Removes \a n characters from the string, starting at the given \a
1672 position index, and returns a reference to the string.
1674 If the specified \a position index is within the string, but \a
1675 position + \a n is beyond the end of the string, the string is
1676 truncated at the specified \a position.
1678 \snippet doc/src/snippets/qstring/main.cpp 37
1680 \sa insert(), replace()
1682 QString &QString::remove(int pos, int len)
1684 if (pos < 0) // count from end of string
1686 if (pos < 0 || pos >= d->size) {
1688 } else if (len >= d->size - pos) {
1689 resize(pos); // truncate
1690 } else if (len > 0) {
1692 memmove(d->data() + pos, d->data() + pos + len,
1693 (d->size - pos - len + 1) * sizeof(ushort));
1700 Removes every occurrence of the given \a str string in this
1701 string, and returns a reference to this string.
1703 If \a cs is Qt::CaseSensitive (default), the search is
1704 case sensitive; otherwise the search is case insensitive.
1706 This is the same as \c replace(str, "", cs).
1710 QString &QString::remove(const QString &str, Qt::CaseSensitivity cs)
1714 while ((i = indexOf(str, i, cs)) != -1)
1715 remove(i, str.d->size);
1721 Removes every occurrence of the character \a ch in this string, and
1722 returns a reference to this string.
1724 If \a cs is Qt::CaseSensitive (default), the search is case
1725 sensitive; otherwise the search is case insensitive.
1729 \snippet doc/src/snippets/qstring/main.cpp 38
1731 This is the same as \c replace(ch, "", cs).
1735 QString &QString::remove(QChar ch, Qt::CaseSensitivity cs)
1738 ushort c = ch.unicode();
1739 if (cs == Qt::CaseSensitive) {
1741 if (d->data()[i] == ch)
1748 if (foldCase(d->data()[i]) == c)
1757 \fn QString &QString::remove(const QRegExp &rx)
1759 Removes every occurrence of the regular expression \a rx in the
1760 string, and returns a reference to the string. For example:
1762 \snippet doc/src/snippets/qstring/main.cpp 39
1764 \sa indexOf(), lastIndexOf(), replace()
1768 \fn QString &QString::replace(int position, int n, const QString &after)
1770 Replaces \a n characters beginning at index \a position with
1771 the string \a after and returns a reference to this string.
1775 \snippet doc/src/snippets/qstring/main.cpp 40
1777 \sa insert(), remove()
1779 QString &QString::replace(int pos, int len, const QString &after)
1781 QString copy = after;
1782 return replace(pos, len, copy.constData(), copy.length());
1786 \fn QString &QString::replace(int position, int n, const QChar *unicode, int size)
1788 Replaces \a n characters beginning at index \a position with the
1789 first \a size characters of the QChar array \a unicode and returns a
1790 reference to this string.
1792 QString &QString::replace(int pos, int len, const QChar *unicode, int size)
1794 if (pos < 0 || pos > d->size)
1796 if (pos + len > d->size)
1797 len = d->size - pos;
1800 replace_helper(&index, 1, len, unicode, size);
1805 \fn QString &QString::replace(int position, int n, QChar after)
1808 Replaces \a n characters beginning at index \a position with the
1809 character \a after and returns a reference to this string.
1811 QString &QString::replace(int pos, int len, QChar after)
1813 return replace(pos, len, &after, 1);
1818 Replaces every occurrence of the string \a before with the string \a
1819 after and returns a reference to this string.
1821 If \a cs is Qt::CaseSensitive (default), the search is case
1822 sensitive; otherwise the search is case insensitive.
1826 \snippet doc/src/snippets/qstring/main.cpp 41
1828 \note The replacement text is not rescanned after it is inserted.
1832 \snippet doc/src/snippets/qstring/main.cpp 86
1834 QString &QString::replace(const QString &before, const QString &after, Qt::CaseSensitivity cs)
1836 return replace(before.constData(), before.size(), after.constData(), after.size(), cs);
1842 void QString::replace_helper(uint *indices, int nIndices, int blen, const QChar *after, int alen)
1844 // copy *after in case it lies inside our own d->data() area
1845 // (which we could possibly invalidate via a realloc or corrupt via memcpy operations.)
1846 QChar *afterBuffer = const_cast<QChar *>(after);
1847 if (after >= reinterpret_cast<QChar *>(d->data()) && after < reinterpret_cast<QChar *>(d->data()) + d->size) {
1848 afterBuffer = static_cast<QChar *>(::malloc(alen*sizeof(QChar)));
1849 Q_CHECK_PTR(afterBuffer);
1850 ::memcpy(afterBuffer, after, alen*sizeof(QChar));
1857 for (int i = 0; i < nIndices; ++i)
1858 memcpy(d->data() + indices[i], afterBuffer, alen * sizeof(QChar));
1859 } else if (alen < blen) {
1860 // replace from front
1862 uint to = indices[0];
1864 memcpy(d->data()+to, after, alen*sizeof(QChar));
1866 uint movestart = indices[0] + blen;
1867 for (int i = 1; i < nIndices; ++i) {
1868 int msize = indices[i] - movestart;
1870 memmove(d->data() + to, d->data() + movestart, msize * sizeof(QChar));
1874 memcpy(d->data() + to, afterBuffer, alen*sizeof(QChar));
1877 movestart = indices[i] + blen;
1879 int msize = d->size - movestart;
1881 memmove(d->data() + to, d->data() + movestart, msize * sizeof(QChar));
1882 resize(d->size - nIndices*(blen-alen));
1884 // replace from back
1885 int adjust = nIndices*(alen-blen);
1886 int newLen = d->size + adjust;
1887 int moveend = d->size;
1892 int movestart = indices[nIndices] + blen;
1893 int insertstart = indices[nIndices] + nIndices*(alen-blen);
1894 int moveto = insertstart + alen;
1895 memmove(d->data() + moveto, d->data() + movestart,
1896 (moveend - movestart)*sizeof(QChar));
1897 memcpy(d->data() + insertstart, afterBuffer, alen*sizeof(QChar));
1898 moveend = movestart-blen;
1901 } QT_CATCH(const std::bad_alloc &) {
1902 if (afterBuffer != after)
1903 ::free(afterBuffer);
1906 if (afterBuffer != after)
1907 ::free(afterBuffer);
1914 Replaces each occurrence in this string of the first \a blen
1915 characters of \a before with the first \a alen characters of \a
1916 after and returns a reference to this string.
1918 If \a cs is Qt::CaseSensitive (default), the search is case
1919 sensitive; otherwise the search is case insensitive.
1921 QString &QString::replace(const QChar *before, int blen,
1922 const QChar *after, int alen,
1923 Qt::CaseSensitivity cs)
1929 if (cs == Qt::CaseSensitive && before == after && blen == alen)
1932 if (alen == 0 && blen == 0)
1935 QStringMatcher matcher(before, blen, cs);
1941 while (pos < 1023) {
1942 index = matcher.indexIn(*this, index);
1945 indices[pos++] = index;
1947 // avoid infinite loop
1954 replace_helper(indices, pos, blen, after, alen);
1958 // index has to be adjusted in case we get back into the loop above.
1959 index += pos*(alen-blen);
1967 Replaces every occurrence of the character \a ch in the string with
1968 \a after and returns a reference to this string.
1970 If \a cs is Qt::CaseSensitive (default), the search is case
1971 sensitive; otherwise the search is case insensitive.
1973 QString& QString::replace(QChar ch, const QString &after, Qt::CaseSensitivity cs)
1975 if (after.d->size == 0)
1976 return remove(ch, cs);
1978 if (after.d->size == 1)
1979 return replace(ch, after.d->data()[0], cs);
1984 ushort cc = (cs == Qt::CaseSensitive ? ch.unicode() : ch.toCaseFolded().unicode());
1990 if (cs == Qt::CaseSensitive) {
1991 while (pos < 1023 && index < d->size) {
1992 if (d->data()[index] == cc)
1993 indices[pos++] = index;
1997 while (pos < 1023 && index < d->size) {
1998 if (QChar::toCaseFolded(d->data()[index]) == cc)
1999 indices[pos++] = index;
2006 replace_helper(indices, pos, 1, after.constData(), after.d->size);
2010 // index has to be adjusted in case we get back into the loop above.
2011 index += pos*(after.d->size - 1);
2018 Replaces every occurrence of the character \a before with the
2019 character \a after and returns a reference to this string.
2021 If \a cs is Qt::CaseSensitive (default), the search is case
2022 sensitive; otherwise the search is case insensitive.
2024 QString& QString::replace(QChar before, QChar after, Qt::CaseSensitivity cs)
2026 ushort a = after.unicode();
2027 ushort b = before.unicode();
2030 ushort *i = d->data();
2031 const ushort *e = i + d->size;
2032 if (cs == Qt::CaseSensitive) {
2039 if (foldCase(*i) == b)
2050 Replaces every occurrence of the string \a before with the string \a
2051 after and returns a reference to this string.
2053 If \a cs is Qt::CaseSensitive (default), the search is case
2054 sensitive; otherwise the search is case insensitive.
2056 \note The text is not rescanned after a replacement.
2058 QString &QString::replace(const QLatin1String &before,
2059 const QLatin1String &after,
2060 Qt::CaseSensitivity cs)
2062 int alen = after.size();
2063 QVarLengthArray<ushort> a(alen);
2064 for (int i = 0; i < alen; ++i)
2065 a[i] = (uchar)after.latin1()[i];
2066 int blen = before.size();
2067 QVarLengthArray<ushort> b(blen);
2068 for (int i = 0; i < blen; ++i)
2069 b[i] = (uchar)before.latin1()[i];
2070 return replace((const QChar *)b.data(), blen, (const QChar *)a.data(), alen, cs);
2077 Replaces every occurrence of the string \a before with the string \a
2078 after and returns a reference to this string.
2080 If \a cs is Qt::CaseSensitive (default), the search is case
2081 sensitive; otherwise the search is case insensitive.
2083 \note The text is not rescanned after a replacement.
2085 QString &QString::replace(const QLatin1String &before,
2086 const QString &after,
2087 Qt::CaseSensitivity cs)
2089 int blen = before.size();
2090 QVarLengthArray<ushort> b(blen);
2091 for (int i = 0; i < blen; ++i)
2092 b[i] = (uchar)before.latin1()[i];
2093 return replace((const QChar *)b.data(), blen, after.constData(), after.d->size, cs);
2100 Replaces every occurrence of the string \a before with the string \a
2101 after and returns a reference to this string.
2103 If \a cs is Qt::CaseSensitive (default), the search is case
2104 sensitive; otherwise the search is case insensitive.
2106 \note The text is not rescanned after a replacement.
2108 QString &QString::replace(const QString &before,
2109 const QLatin1String &after,
2110 Qt::CaseSensitivity cs)
2112 int alen = after.size();
2113 QVarLengthArray<ushort> a(alen);
2114 for (int i = 0; i < alen; ++i)
2115 a[i] = (uchar)after.latin1()[i];
2116 return replace(before.constData(), before.d->size, (const QChar *)a.data(), alen, cs);
2123 Replaces every occurrence of the character \a c with the string \a
2124 after and returns a reference to this string.
2126 If \a cs is Qt::CaseSensitive (default), the search is case
2127 sensitive; otherwise the search is case insensitive.
2129 \note The text is not rescanned after a replacement.
2131 QString &QString::replace(QChar c, const QLatin1String &after, Qt::CaseSensitivity cs)
2133 int alen = after.size();
2134 QVarLengthArray<ushort> a(alen);
2135 for (int i = 0; i < alen; ++i)
2136 a[i] = (uchar)after.latin1()[i];
2137 return replace(&c, 1, (const QChar *)a.data(), alen, cs);
2142 Returns true if string \a other is equal to this string; otherwise
2145 The comparison is based exclusively on the numeric Unicode values of
2146 the characters and is very fast, but is not what a human would
2147 expect. Consider sorting user-interface strings with
2148 localeAwareCompare().
2150 bool QString::operator==(const QString &other) const
2152 if (d->size != other.d->size)
2155 return qMemEquals(d->data(), other.d->data(), d->size);
2159 \overload operator==()
2161 bool QString::operator==(const QLatin1String &other) const
2163 if (d->size != other.size())
2169 const ushort *uc = d->data();
2170 const ushort *e = uc + d->size;
2171 const uchar *c = (uchar *)other.latin1();
2182 /*! \fn bool QString::operator==(const QByteArray &other) const
2184 \overload operator==()
2186 The \a other byte array is converted to a QString using the
2187 fromAscii() function. This function stops conversion at the
2188 first NUL character found, or the end of the byte array.
2190 You can disable this operator by defining \c
2191 QT_NO_CAST_FROM_ASCII when you compile your applications. This
2192 can be useful if you want to ensure that all user-visible strings
2193 go through QObject::tr(), for example.
2196 /*! \fn bool QString::operator==(const char *other) const
2198 \overload operator==()
2200 The \a other const char pointer is converted to a QString using
2201 the fromAscii() function.
2203 You can disable this operator by defining \c
2204 QT_NO_CAST_FROM_ASCII when you compile your applications. This
2205 can be useful if you want to ensure that all user-visible strings
2206 go through QObject::tr(), for example.
2210 Returns true if this string is lexically less than string \a
2211 other; otherwise returns false.
2213 The comparison is based exclusively on the numeric Unicode values
2214 of the characters and is very fast, but is not what a human would
2215 expect. Consider sorting user-interface strings using the
2216 QString::localeAwareCompare() function.
2218 bool QString::operator<(const QString &other) const
2220 return ucstrcmp(constData(), length(), other.constData(), other.length()) < 0;
2224 \overload operator<()
2226 bool QString::operator<(const QLatin1String &other) const
2228 const uchar *c = (uchar *) other.latin1();
2232 const ushort *uc = d->data();
2233 const ushort *e = uc + qMin(d->size, other.size());
2241 return (uc == e ? d->size < other.size() : *uc < *c);
2244 /*! \fn bool QString::operator<(const QByteArray &other) const
2246 \overload operator<()
2248 The \a other byte array is converted to a QString using the
2249 fromAscii() function. If any NUL characters ('\0') are embedded
2250 in the byte array, they will be included in the transformation.
2252 You can disable this operator by defining \c
2253 QT_NO_CAST_FROM_ASCII when you compile your applications. This
2254 can be useful if you want to ensure that all user-visible strings
2255 go through QObject::tr(), for example.
2258 /*! \fn bool QString::operator<(const char *other) const
2260 \overload operator<()
2262 The \a other const char pointer is converted to a QString using
2263 the fromAscii() function.
2265 You can disable this operator by defining \c
2266 QT_NO_CAST_FROM_ASCII when you compile your applications. This
2267 can be useful if you want to ensure that all user-visible strings
2268 go through QObject::tr(), for example.
2271 /*! \fn bool QString::operator<=(const QString &other) const
2273 Returns true if this string is lexically less than or equal to
2274 string \a other; otherwise returns false.
2276 The comparison is based exclusively on the numeric Unicode values
2277 of the characters and is very fast, but is not what a human would
2278 expect. Consider sorting user-interface strings with
2279 localeAwareCompare().
2282 /*! \fn bool QString::operator<=(const QLatin1String &other) const
2284 \overload operator<=()
2287 /*! \fn bool QString::operator<=(const QByteArray &other) const
2289 \overload operator<=()
2291 The \a other byte array is converted to a QString using the
2292 fromAscii() function. If any NUL characters ('\0') are embedded
2293 in the byte array, they will be included in the transformation.
2295 You can disable this operator by defining \c
2296 QT_NO_CAST_FROM_ASCII when you compile your applications. This
2297 can be useful if you want to ensure that all user-visible strings
2298 go through QObject::tr(), for example.
2301 /*! \fn bool QString::operator<=(const char *other) const
2303 \overload operator<=()
2305 The \a other const char pointer is converted to a QString using
2306 the fromAscii() function.
2308 You can disable this operator by defining \c
2309 QT_NO_CAST_FROM_ASCII when you compile your applications. This
2310 can be useful if you want to ensure that all user-visible strings
2311 go through QObject::tr(), for example.
2314 /*! \fn bool QString::operator>(const QString &other) const
2316 Returns true if this string is lexically greater than string \a
2317 other; otherwise returns false.
2319 The comparison is based exclusively on the numeric Unicode values
2320 of the characters and is very fast, but is not what a human would
2321 expect. Consider sorting user-interface strings with
2322 localeAwareCompare().
2326 \overload operator>()
2328 bool QString::operator>(const QLatin1String &other) const
2330 const uchar *c = (uchar *) other.latin1();
2331 if (!c || *c == '\0')
2334 const ushort *uc = d->data();
2335 const ushort *e = uc + qMin(d->size, other.size());
2343 return (uc == e) ? d->size > other.size() : *uc > *c;
2346 /*! \fn bool QString::operator>(const QByteArray &other) const
2348 \overload operator>()
2350 The \a other byte array is converted to a QString using the
2351 fromAscii() function. If any NUL characters ('\0') are embedded
2352 in the byte array, they will be included in the transformation.
2354 You can disable this operator by defining \c
2355 QT_NO_CAST_FROM_ASCII when you compile your applications. This
2356 can be useful if you want to ensure that all user-visible strings
2357 go through QObject::tr(), for example.
2360 /*! \fn bool QString::operator>(const char *other) const
2362 \overload operator>()
2364 The \a other const char pointer is converted to a QString using
2365 the fromAscii() function.
2367 You can disable this operator by defining \c QT_NO_CAST_FROM_ASCII
2368 when you compile your applications. This can be useful if you want
2369 to ensure that all user-visible strings go through QObject::tr(),
2373 /*! \fn bool QString::operator>=(const QString &other) const
2375 Returns true if this string is lexically greater than or equal to
2376 string \a other; otherwise returns false.
2378 The comparison is based exclusively on the numeric Unicode values
2379 of the characters and is very fast, but is not what a human would
2380 expect. Consider sorting user-interface strings with
2381 localeAwareCompare().
2384 /*! \fn bool QString::operator>=(const QLatin1String &other) const
2386 \overload operator>=()
2389 /*! \fn bool QString::operator>=(const QByteArray &other) const
2391 \overload operator>=()
2393 The \a other byte array is converted to a QString using the
2394 fromAscii() function. If any NUL characters ('\0') are embedded in
2395 the byte array, they will be included in the transformation.
2397 You can disable this operator by defining \c QT_NO_CAST_FROM_ASCII
2398 when you compile your applications. This can be useful if you want
2399 to ensure that all user-visible strings go through QObject::tr(),
2403 /*! \fn bool QString::operator>=(const char *other) const
2405 \overload operator>=()
2407 The \a other const char pointer is converted to a QString using
2408 the fromAscii() function.
2410 You can disable this operator by defining \c QT_NO_CAST_FROM_ASCII
2411 when you compile your applications. This can be useful if you want
2412 to ensure that all user-visible strings go through QObject::tr(),
2416 /*! \fn bool QString::operator!=(const QString &other) const
2418 Returns true if this string is not equal to string \a other;
2419 otherwise returns false.
2421 The comparison is based exclusively on the numeric Unicode values
2422 of the characters and is very fast, but is not what a human would
2423 expect. Consider sorting user-interface strings with
2424 localeAwareCompare().
2427 /*! \fn bool QString::operator!=(const QLatin1String &other) const
2429 \overload operator!=()
2432 /*! \fn bool QString::operator!=(const QByteArray &other) const
2434 \overload operator!=()
2436 The \a other byte array is converted to a QString using the
2437 fromAscii() function. If any NUL characters ('\0') are embedded
2438 in the byte array, they will be included in the transformation.
2440 You can disable this operator by defining \c QT_NO_CAST_FROM_ASCII
2441 when you compile your applications. This can be useful if you want
2442 to ensure that all user-visible strings go through QObject::tr(),
2446 /*! \fn bool QString::operator!=(const char *other) const
2448 \overload operator!=()
2450 The \a other const char pointer is converted to a QString using
2451 the fromAscii() function.
2453 You can disable this operator by defining \c
2454 QT_NO_CAST_FROM_ASCII when you compile your applications. This
2455 can be useful if you want to ensure that all user-visible strings
2456 go through QObject::tr(), for example.
2460 Returns the index position of the first occurrence of the string \a
2461 str in this string, searching forward from index position \a
2462 from. Returns -1 if \a str is not found.
2464 If \a cs is Qt::CaseSensitive (default), the search is case
2465 sensitive; otherwise the search is case insensitive.
2469 \snippet doc/src/snippets/qstring/main.cpp 24
2471 If \a from is -1, the search starts at the last character; if it is
2472 -2, at the next to last character and so on.
2474 \sa lastIndexOf(), contains(), count()
2476 int QString::indexOf(const QString &str, int from, Qt::CaseSensitivity cs) const
2478 return qFindString(unicode(), length(), from, str.unicode(), str.length(), cs);
2483 Returns the index position of the first occurrence of the string \a
2484 str in this string, searching forward from index position \a
2485 from. Returns -1 if \a str is not found.
2487 If \a cs is Qt::CaseSensitive (default), the search is case
2488 sensitive; otherwise the search is case insensitive.
2492 \snippet doc/src/snippets/qstring/main.cpp 24
2494 If \a from is -1, the search starts at the last character; if it is
2495 -2, at the next to last character and so on.
2497 \sa lastIndexOf(), contains(), count()
2500 int QString::indexOf(const QLatin1String &str, int from, Qt::CaseSensitivity cs) const
2502 return qt_find_latin1_string(unicode(), size(), str, from, cs);
2506 const QChar *haystack0, int haystackLen, int from,
2507 const QChar *needle0, int needleLen, Qt::CaseSensitivity cs)
2509 const int l = haystackLen;
2510 const int sl = needleLen;
2513 if (uint(sl + from) > (uint)l)
2521 return findChar(haystack0, haystackLen, needle0[0], from, cs);
2524 We use the Boyer-Moore algorithm in cases where the overhead
2525 for the skip table should pay off, otherwise we use a simple
2528 if (l > 500 && sl > 5)
2529 return qFindStringBoyerMoore(haystack0, haystackLen, from,
2530 needle0, needleLen, cs);
2533 We use some hashing for efficiency's sake. Instead of
2534 comparing strings, we compare the hash value of str with that
2535 of a part of this QString. Only if that matches, we call
2536 ucstrncmp() or ucstrnicmp().
2538 const ushort *needle = (const ushort *)needle0;
2539 const ushort *haystack = (const ushort *)haystack0 + from;
2540 const ushort *end = (const ushort *)haystack0 + (l-sl);
2541 const int sl_minus_1 = sl-1;
2542 int hashNeedle = 0, hashHaystack = 0, idx;
2544 if (cs == Qt::CaseSensitive) {
2545 for (idx = 0; idx < sl; ++idx) {
2546 hashNeedle = ((hashNeedle<<1) + needle[idx]);
2547 hashHaystack = ((hashHaystack<<1) + haystack[idx]);
2549 hashHaystack -= haystack[sl_minus_1];
2551 while (haystack <= end) {
2552 hashHaystack += haystack[sl_minus_1];
2553 if (hashHaystack == hashNeedle
2554 && ucstrncmp((const QChar *)needle, (const QChar *)haystack, sl) == 0)
2555 return haystack - (const ushort *)haystack0;
2561 const ushort *haystack_start = (const ushort *)haystack0;
2562 for (idx = 0; idx < sl; ++idx) {
2563 hashNeedle = (hashNeedle<<1) + foldCase(needle + idx, needle);
2564 hashHaystack = (hashHaystack<<1) + foldCase(haystack + idx, haystack_start);
2566 hashHaystack -= foldCase(haystack + sl_minus_1, haystack_start);
2568 while (haystack <= end) {
2569 hashHaystack += foldCase(haystack + sl_minus_1, haystack_start);
2570 if (hashHaystack == hashNeedle && ucstrnicmp(needle, haystack, sl) == 0)
2571 return haystack - (const ushort *)haystack0;
2573 REHASH(foldCase(haystack, haystack_start));
2583 Returns the index position of the first occurrence of the
2584 character \a ch in the string, searching forward from index
2585 position \a from. Returns -1 if \a ch could not be found.
2587 int QString::indexOf(QChar ch, int from, Qt::CaseSensitivity cs) const
2589 return findChar(unicode(), length(), ch, from, cs);
2597 Returns the index position of the first occurrence of the string
2598 reference \a str in this string, searching forward from index
2599 position \a from. Returns -1 if \a str is not found.
2601 If \a cs is Qt::CaseSensitive (default), the search is case
2602 sensitive; otherwise the search is case insensitive.
2604 int QString::indexOf(const QStringRef &str, int from, Qt::CaseSensitivity cs) const
2606 return qFindString(unicode(), length(), from, str.unicode(), str.length(), cs);
2609 static int lastIndexOfHelper(const ushort *haystack, int from, const ushort *needle, int sl, Qt::CaseSensitivity cs)
2612 See indexOf() for explanations.
2615 const ushort *end = haystack;
2617 const int sl_minus_1 = sl-1;
2618 const ushort *n = needle+sl_minus_1;
2619 const ushort *h = haystack+sl_minus_1;
2620 int hashNeedle = 0, hashHaystack = 0, idx;
2622 if (cs == Qt::CaseSensitive) {
2623 for (idx = 0; idx < sl; ++idx) {
2624 hashNeedle = ((hashNeedle<<1) + *(n-idx));
2625 hashHaystack = ((hashHaystack<<1) + *(h-idx));
2627 hashHaystack -= *haystack;
2629 while (haystack >= end) {
2630 hashHaystack += *haystack;
2631 if (hashHaystack == hashNeedle
2632 && ucstrncmp((const QChar *)needle, (const QChar *)haystack, sl) == 0)
2633 return haystack - end;
2635 REHASH(haystack[sl]);
2638 for (idx = 0; idx < sl; ++idx) {
2639 hashNeedle = ((hashNeedle<<1) + foldCase(n-idx, needle));
2640 hashHaystack = ((hashHaystack<<1) + foldCase(h-idx, end));
2642 hashHaystack -= foldCase(haystack, end);
2644 while (haystack >= end) {
2645 hashHaystack += foldCase(haystack, end);
2646 if (hashHaystack == hashNeedle && ucstrnicmp(needle, haystack, sl) == 0)
2647 return haystack - end;
2649 REHASH(foldCase(haystack + sl, end));
2656 Returns the index position of the last occurrence of the string \a
2657 str in this string, searching backward from index position \a
2658 from. If \a from is -1 (default), the search starts at the last
2659 character; if \a from is -2, at the next to last character and so
2660 on. Returns -1 if \a str is not found.
2662 If \a cs is Qt::CaseSensitive (default), the search is case
2663 sensitive; otherwise the search is case insensitive.
2667 \snippet doc/src/snippets/qstring/main.cpp 29
2669 \sa indexOf(), contains(), count()
2671 int QString::lastIndexOf(const QString &str, int from, Qt::CaseSensitivity cs) const
2673 const int sl = str.d->size;
2675 return lastIndexOf(QChar(str.d->data()[0]), from, cs);
2677 const int l = d->size;
2681 if (from == l && sl == 0)
2683 if (from < 0 || from >= l || delta < 0)
2688 return lastIndexOfHelper(d->data(), from, str.d->data(), str.d->size, cs);
2693 \overload lastIndexOf()
2695 Returns the index position of the last occurrence of the string \a
2696 str in this string, searching backward from index position \a
2697 from. If \a from is -1 (default), the search starts at the last
2698 character; if \a from is -2, at the next to last character and so
2699 on. Returns -1 if \a str is not found.
2701 If \a cs is Qt::CaseSensitive (default), the search is case
2702 sensitive; otherwise the search is case insensitive.
2706 \snippet doc/src/snippets/qstring/main.cpp 29
2708 \sa indexOf(), contains(), count()
2710 int QString::lastIndexOf(const QLatin1String &str, int from, Qt::CaseSensitivity cs) const
2712 const int sl = str.size();
2714 return lastIndexOf(QLatin1Char(str.latin1()[0]), from, cs);
2716 const int l = d->size;
2720 if (from == l && sl == 0)
2722 if (from < 0 || from >= l || delta < 0)
2727 QVarLengthArray<ushort> s(sl);
2728 for (int i = 0; i < sl; ++i)
2729 s[i] = str.latin1()[i];
2731 return lastIndexOfHelper(d->data(), from, s.data(), sl, cs);
2735 \overload lastIndexOf()
2737 Returns the index position of the last occurrence of the character
2738 \a ch, searching backward from position \a from.
2740 int QString::lastIndexOf(QChar ch, int from, Qt::CaseSensitivity cs) const
2742 return qt_last_index_of(unicode(), size(), ch, from, cs);
2747 \overload lastIndexOf()
2749 Returns the index position of the last occurrence of the string
2750 reference \a str in this string, searching backward from index
2751 position \a from. If \a from is -1 (default), the search starts at
2752 the last character; if \a from is -2, at the next to last character
2753 and so on. Returns -1 if \a str is not found.
2755 If \a cs is Qt::CaseSensitive (default), the search is case
2756 sensitive; otherwise the search is case insensitive.
2758 \sa indexOf(), contains(), count()
2760 int QString::lastIndexOf(const QStringRef &str, int from, Qt::CaseSensitivity cs) const
2762 const int sl = str.size();
2764 return lastIndexOf(str.at(0), from, cs);
2766 const int l = d->size;
2770 if (from == l && sl == 0)
2772 if (from < 0 || from >= l || delta < 0)
2777 return lastIndexOfHelper(d->data(), from, reinterpret_cast<const ushort*>(str.unicode()),
2781 #ifndef QT_NO_REGEXP
2782 struct QStringCapture
2792 Replaces every occurrence of the regular expression \a rx in the
2793 string with \a after. Returns a reference to the string. For
2796 \snippet doc/src/snippets/qstring/main.cpp 42
2798 For regular expressions containing \l{capturing parentheses},
2799 occurrences of \bold{\\1}, \bold{\\2}, ..., in \a after are replaced
2800 with \a{rx}.cap(1), cap(2), ...
2802 \snippet doc/src/snippets/qstring/main.cpp 43
2804 \sa indexOf(), lastIndexOf(), remove(), QRegExp::cap()
2806 QString& QString::replace(const QRegExp &rx, const QString &after)
2810 if (isEmpty() && rx2.indexIn(*this) == -1)
2816 int numCaptures = rx2.captureCount();
2817 int al = after.length();
2818 QRegExp::CaretMode caretMode = QRegExp::CaretAtZero;
2820 if (numCaptures > 0) {
2821 const QChar *uc = after.unicode();
2822 int numBackRefs = 0;
2824 for (int i = 0; i < al - 1; i++) {
2825 if (uc[i] == QLatin1Char('\\')) {
2826 int no = uc[i + 1].digitValue();
2827 if (no > 0 && no <= numCaptures)
2833 This is the harder case where we have back-references.
2835 if (numBackRefs > 0) {
2836 QVarLengthArray<QStringCapture, 16> captures(numBackRefs);
2839 for (int i = 0; i < al - 1; i++) {
2840 if (uc[i] == QLatin1Char('\\')) {
2841 int no = uc[i + 1].digitValue();
2842 if (no > 0 && no <= numCaptures) {
2843 QStringCapture capture;
2848 int secondDigit = uc[i + 2].digitValue();
2849 if (secondDigit != -1 && ((no * 10) + secondDigit) <= numCaptures) {
2850 no = (no * 10) + secondDigit;
2856 captures[j++] = capture;
2861 while (index <= length()) {
2862 index = rx2.indexIn(*this, index, caretMode);
2866 QString after2(after);
2867 for (j = numBackRefs - 1; j >= 0; j--) {
2868 const QStringCapture &capture = captures[j];
2869 after2.replace(capture.pos, capture.len, rx2.cap(capture.no));
2872 replace(index, rx2.matchedLength(), after2);
2873 index += after2.length();
2875 // avoid infinite loop on 0-length matches (e.g., QRegExp("[a-z]*"))
2876 if (rx2.matchedLength() == 0)
2879 caretMode = QRegExp::CaretWontMatch;
2886 This is the simple and optimized case where we don't have
2889 while (index != -1) {
2893 } replacements[2048];
2897 while (pos < 2047) {
2898 index = rx2.indexIn(*this, index, caretMode);
2901 int ml = rx2.matchedLength();
2902 replacements[pos].pos = index;
2903 replacements[pos++].length = ml;
2906 // avoid infinite loop
2912 replacements[pos].pos = d->size;
2913 int newlen = d->size + adjust;
2915 // to continue searching at the right position after we did
2916 // the first round of replacements
2920 newstring.reserve(newlen + 1);
2921 QChar *newuc = newstring.data();
2926 int copyend = replacements[i].pos;
2927 int size = copyend - copystart;
2928 memcpy(uc, d->data() + copystart, size * sizeof(QChar));
2930 memcpy(uc, after.d->data(), al * sizeof(QChar));
2932 copystart = copyend + replacements[i].length;
2935 memcpy(uc, d->data() + copystart, (d->size - copystart) * sizeof(QChar));
2936 newstring.resize(newlen);
2938 caretMode = QRegExp::CaretWontMatch;
2945 Returns the number of (potentially overlapping) occurrences of
2946 the string \a str in this string.
2948 If \a cs is Qt::CaseSensitive (default), the search is
2949 case sensitive; otherwise the search is case insensitive.
2951 \sa contains(), indexOf()
2954 int QString::count(const QString &str, Qt::CaseSensitivity cs) const
2956 return qt_string_count(unicode(), size(), str.unicode(), str.size(), cs);
2962 Returns the number of occurrences of character \a ch in the string.
2965 int QString::count(QChar ch, Qt::CaseSensitivity cs) const
2967 return qt_string_count(unicode(), size(), ch, cs);
2973 Returns the number of (potentially overlapping) occurrences of the
2974 string reference \a str in this string.
2976 If \a cs is Qt::CaseSensitive (default), the search is
2977 case sensitive; otherwise the search is case insensitive.
2979 \sa contains(), indexOf()
2981 int QString::count(const QStringRef &str, Qt::CaseSensitivity cs) const
2983 return qt_string_count(unicode(), size(), str.unicode(), str.size(), cs);
2987 /*! \fn bool QString::contains(const QString &str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
2989 Returns true if this string contains an occurrence of the string
2990 \a str; otherwise returns false.
2992 If \a cs is Qt::CaseSensitive (default), the search is
2993 case sensitive; otherwise the search is case insensitive.
2996 \snippet doc/src/snippets/qstring/main.cpp 17
2998 \sa indexOf(), count()
3001 /*! \fn bool QString::contains(QChar ch, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
3003 \overload contains()
3005 Returns true if this string contains an occurrence of the
3006 character \a ch; otherwise returns false.
3009 /*! \fn bool QString::contains(const QStringRef &str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
3012 Returns true if this string contains an occurrence of the string
3013 reference \a str; otherwise returns false.
3015 If \a cs is Qt::CaseSensitive (default), the search is
3016 case sensitive; otherwise the search is case insensitive.
3018 \sa indexOf(), count()
3021 /*! \fn bool QString::contains(const QRegExp &rx) const
3023 \overload contains()
3025 Returns true if the regular expression \a rx matches somewhere in
3026 this string; otherwise returns false.
3029 /*! \fn bool QString::contains(QRegExp &rx) const
3030 \overload contains()
3033 Returns true if the regular expression \a rx matches somewhere in
3034 this string; otherwise returns false.
3036 If there is a match, the \a rx regular expression will contain the
3037 matched captures (see QRegExp::matchedLength, QRegExp::cap).
3040 #ifndef QT_NO_REGEXP
3044 Returns the index position of the first match of the regular
3045 expression \a rx in the string, searching forward from index
3046 position \a from. Returns -1 if \a rx didn't match anywhere.
3050 \snippet doc/src/snippets/qstring/main.cpp 25
3052 int QString::indexOf(const QRegExp& rx, int from) const
3055 return rx2.indexIn(*this, from);
3062 Returns the index position of the first match of the regular
3063 expression \a rx in the string, searching forward from index
3064 position \a from. Returns -1 if \a rx didn't match anywhere.
3066 If there is a match, the \a rx regular expression will contain the
3067 matched captures (see QRegExp::matchedLength, QRegExp::cap).
3071 \snippet doc/src/snippets/qstring/main.cpp 25
3073 int QString::indexOf(QRegExp& rx, int from) const
3075 return rx.indexIn(*this, from);
3079 \overload lastIndexOf()
3081 Returns the index position of the last match of the regular
3082 expression \a rx in the string, searching backward from index
3083 position \a from. Returns -1 if \a rx didn't match anywhere.
3087 \snippet doc/src/snippets/qstring/main.cpp 30
3089 int QString::lastIndexOf(const QRegExp& rx, int from) const
3092 return rx2.lastIndexIn(*this, from);
3096 \overload lastIndexOf()
3099 Returns the index position of the last match of the regular
3100 expression \a rx in the string, searching backward from index
3101 position \a from. Returns -1 if \a rx didn't match anywhere.
3103 If there is a match, the \a rx regular expression will contain the
3104 matched captures (see QRegExp::matchedLength, QRegExp::cap).
3108 \snippet doc/src/snippets/qstring/main.cpp 30
3110 int QString::lastIndexOf(QRegExp& rx, int from) const
3112 return rx.lastIndexIn(*this, from);
3118 Returns the number of times the regular expression \a rx matches
3121 This function counts overlapping matches, so in the example
3122 below, there are four instances of "ana" or "ama":
3124 \snippet doc/src/snippets/qstring/main.cpp 18
3127 int QString::count(const QRegExp& rx) const
3133 while (index < len - 1) { // count overlapping matches
3134 index = rx2.indexIn(*this, index + 1);
3141 #endif // QT_NO_REGEXP
3143 /*! \fn int QString::count() const
3152 \enum QString::SectionFlag
3154 This enum specifies flags that can be used to affect various
3155 aspects of the section() function's behavior with respect to
3156 separators and empty fields.
3158 \value SectionDefault Empty fields are counted, leading and
3159 trailing separators are not included, and the separator is
3160 compared case sensitively.
3162 \value SectionSkipEmpty Treat empty fields as if they don't exist,
3163 i.e. they are not considered as far as \e start and \e end are
3166 \value SectionIncludeLeadingSep Include the leading separator (if
3167 any) in the result string.
3169 \value SectionIncludeTrailingSep Include the trailing separator
3170 (if any) in the result string.
3172 \value SectionCaseInsensitiveSeps Compare the separator
3179 \fn QString QString::section(QChar sep, int start, int end = -1, SectionFlags flags) const
3181 This function returns a section of the string.
3183 This string is treated as a sequence of fields separated by the
3184 character, \a sep. The returned string consists of the fields from
3185 position \a start to position \a end inclusive. If \a end is not
3186 specified, all fields from position \a start to the end of the
3187 string are included. Fields are numbered 0, 1, 2, etc., counting
3188 from the left, and -1, -2, etc., counting from right to left.
3190 The \a flags argument can be used to affect some aspects of the
3191 function's behavior, e.g. whether to be case sensitive, whether
3192 to skip empty fields and how to deal with leading and trailing
3193 separators; see \l{SectionFlags}.
3195 \snippet doc/src/snippets/qstring/main.cpp 52
3197 If \a start or \a end is negative, we count fields from the right
3198 of the string, the right-most field being -1, the one from
3199 right-most field being -2, and so on.
3201 \snippet doc/src/snippets/qstring/main.cpp 53
3209 \snippet doc/src/snippets/qstring/main.cpp 51
3210 \snippet doc/src/snippets/qstring/main.cpp 54
3215 QString QString::section(const QString &sep, int start, int end, SectionFlags flags) const
3217 QStringList sections = split(sep, KeepEmptyParts,
3218 (flags & SectionCaseInsensitiveSeps) ? Qt::CaseInsensitive : Qt::CaseSensitive);
3219 if (sections.isEmpty())
3221 if (!(flags & SectionSkipEmpty)) {
3223 start += sections.count();
3225 end += sections.count();
3228 for (int k=0; k<sections.size(); ++k) {
3229 if (sections.at(k).isEmpty())
3233 start += sections.count() - skip;
3235 end += sections.count() - skip;
3239 int first_i = start, last_i = end;
3240 for (int i = 0; x <= end && i < sections.size(); ++i) {
3241 QString section = sections.at(i);
3242 const bool empty = section.isEmpty();
3252 if (!empty || !(flags & SectionSkipEmpty))
3255 if((flags & SectionIncludeLeadingSep) && first_i)
3257 if((flags & SectionIncludeTrailingSep) && last_i < sections.size()-1)
3262 #ifndef QT_NO_REGEXP
3263 class qt_section_chunk {
3265 qt_section_chunk(int l, QString s) { length = l; string = s; }
3273 This string is treated as a sequence of fields separated by the
3274 regular expression, \a reg.
3276 \snippet doc/src/snippets/qstring/main.cpp 55
3278 \warning Using this QRegExp version is much more expensive than
3279 the overloaded string and character versions.
3281 \sa split() simplified()
3283 QString QString::section(const QRegExp ®, int start, int end, SectionFlags flags) const
3285 const QChar *uc = unicode();
3290 sep.setCaseSensitivity((flags & SectionCaseInsensitiveSeps) ? Qt::CaseInsensitive
3291 : Qt::CaseSensitive);
3293 QList<qt_section_chunk> sections;
3294 int n = length(), m = 0, last_m = 0, last_len = 0;
3295 while ((m = sep.indexIn(*this, m)) != -1) {
3296 sections.append(qt_section_chunk(last_len, QString(uc + last_m, m - last_m)));
3298 last_len = sep.matchedLength();
3299 m += qMax(sep.matchedLength(), 1);
3301 sections.append(qt_section_chunk(last_len, QString(uc + last_m, n - last_m)));
3304 start += sections.count();
3306 end += sections.count();
3310 int first_i = start, last_i = end;
3311 for (int i = 0; x <= end && i < sections.size(); ++i) {
3312 const qt_section_chunk §ion = sections.at(i);
3313 const bool empty = (section.length == section.string.length());
3320 ret += section.string;
3322 ret += section.string.mid(section.length);
3324 if (!empty || !(flags & SectionSkipEmpty))
3327 if((flags & SectionIncludeLeadingSep) && first_i < sections.size()) {
3328 const qt_section_chunk §ion = sections.at(first_i);
3329 ret.prepend(section.string.left(section.length));
3331 if((flags & SectionIncludeTrailingSep) && last_i+1 <= sections.size()-1) {
3332 const qt_section_chunk §ion = sections.at(last_i+1);
3333 ret += section.string.left(section.length);
3340 Returns a substring that contains the \a n leftmost characters
3343 The entire string is returned if \a n is greater than size() or
3346 \snippet doc/src/snippets/qstring/main.cpp 31
3348 \sa right(), mid(), startsWith()
3350 QString QString::left(int n) const
3352 if (n >= d->size || n < 0)
3354 return QString((const QChar*) d->data(), n);
3358 Returns a substring that contains the \a n rightmost characters
3361 The entire string is returned if \a n is greater than size() or
3364 \snippet doc/src/snippets/qstring/main.cpp 48
3366 \sa left(), mid(), endsWith()
3368 QString QString::right(int n) const
3370 if (n >= d->size || n < 0)
3372 return QString((const QChar*) d->data() + d->size - n, n);
3376 Returns a string that contains \a n characters of this string,
3377 starting at the specified \a position index.
3379 Returns a null string if the \a position index exceeds the
3380 length of the string. If there are less than \a n characters
3381 available in the string starting at the given \a position, or if
3382 \a n is -1 (default), the function returns all characters that
3383 are available from the specified \a position.
3387 \snippet doc/src/snippets/qstring/main.cpp 34
3392 QString QString::mid(int position, int n) const
3394 if (d == &shared_null.str || position > d->size)
3397 n = d->size - position;
3402 if (n + position > d->size)
3403 n = d->size - position;
3404 if (position == 0 && n == d->size)
3406 return QString((const QChar*) d->data() + position, n);
3410 Returns true if the string starts with \a s; otherwise returns
3413 If \a cs is Qt::CaseSensitive (default), the search is
3414 case sensitive; otherwise the search is case insensitive.
3416 \snippet doc/src/snippets/qstring/main.cpp 65
3420 bool QString::startsWith(const QString& s, Qt::CaseSensitivity cs) const
3422 return qt_starts_with(isNull() ? 0 : unicode(), size(),
3423 s.isNull() ? 0 : s.unicode(), s.size(), cs);
3427 \overload startsWith()
3429 bool QString::startsWith(const QLatin1String& s, Qt::CaseSensitivity cs) const
3431 return qt_starts_with(isNull() ? 0 : unicode(), size(), s, cs);
3435 \overload startsWith()
3437 Returns true if the string starts with \a c; otherwise returns
3440 bool QString::startsWith(QChar c, Qt::CaseSensitivity cs) const
3443 && (cs == Qt::CaseSensitive
3445 : foldCase(d->data()[0]) == foldCase(c.unicode()));
3451 Returns true if the string starts with the string reference \a s;
3452 otherwise returns false.
3454 If \a cs is Qt::CaseSensitive (default), the search is case
3455 sensitive; otherwise the search is case insensitive.
3459 bool QString::startsWith(const QStringRef &s, Qt::CaseSensitivity cs) const
3461 return qt_starts_with(isNull() ? 0 : unicode(), size(),
3462 s.isNull() ? 0 : s.unicode(), s.size(), cs);
3466 Returns true if the string ends with \a s; otherwise returns
3469 If \a cs is Qt::CaseSensitive (default), the search is case
3470 sensitive; otherwise the search is case insensitive.
3472 \snippet doc/src/snippets/qstring/main.cpp 20
3476 bool QString::endsWith(const QString& s, Qt::CaseSensitivity cs) const
3478 return qt_ends_with(isNull() ? 0 : unicode(), size(),
3479 s.isNull() ? 0 : s.unicode(), s.size(), cs);
3484 \overload endsWith()
3485 Returns true if the string ends with the string reference \a s;
3486 otherwise returns false.
3488 If \a cs is Qt::CaseSensitive (default), the search is case
3489 sensitive; otherwise the search is case insensitive.
3493 bool QString::endsWith(const QStringRef &s, Qt::CaseSensitivity cs) const
3495 return qt_ends_with(isNull() ? 0 : unicode(), size(),
3496 s.isNull() ? 0 : s.unicode(), s.size(), cs);
3501 \overload endsWith()
3503 bool QString::endsWith(const QLatin1String& s, Qt::CaseSensitivity cs) const
3505 return qt_ends_with(isNull() ? 0 : unicode(), size(), s, cs);
3509 Returns true if the string ends with \a c; otherwise returns
3512 \overload endsWith()
3514 bool QString::endsWith(QChar c, Qt::CaseSensitivity cs) const
3517 && (cs == Qt::CaseSensitive
3518 ? d->data()[d->size - 1] == c
3519 : foldCase(d->data()[d->size - 1]) == foldCase(c.unicode()));
3523 #if defined(QT_ALWAYS_HAVE_SSE2)
3524 static inline __m128i mergeQuestionMarks(__m128i chunk)
3526 const __m128i questionMark = _mm_set1_epi16('?');
3529 // compare the unsigned shorts for the range 0x0100-0xFFFF
3530 // note on the use of _mm_cmpestrm:
3531 // The MSDN documentation online (http://technet.microsoft.com/en-us/library/bb514080.aspx)
3532 // says for range search the following:
3533 // For each character c in a, determine whether b0 <= c <= b1 or b2 <= c <= b3
3535 // However, all examples on the Internet, including from Intel
3536 // (see http://software.intel.com/en-us/articles/xml-parsing-accelerator-with-intel-streaming-simd-extensions-4-intel-sse4/)
3537 // put the range to be searched first
3539 // Disassembly and instruction-level debugging with GCC and ICC show
3540 // that they are doing the right thing. Inverting the arguments in the
3541 // instruction does cause a bunch of test failures.
3543 const int mode = _SIDD_UWORD_OPS | _SIDD_CMP_RANGES | _SIDD_UNIT_MASK;
3544 const __m128i rangeMatch = _mm_cvtsi32_si128(0xffff0100);
3545 const __m128i offLimitMask = _mm_cmpestrm(rangeMatch, 2, chunk, 8, mode);
3547 // replace the non-Latin 1 characters in the chunk with question marks
3548 chunk = _mm_blendv_epi8(chunk, questionMark, offLimitMask);
3550 // SSE has no compare instruction for unsigned comparison.
3551 // The variables must be shiffted + 0x8000 to be compared
3552 const __m128i signedBitOffset = _mm_set1_epi16(0x8000);
3553 const __m128i thresholdMask = _mm_set1_epi16(0xff + 0x8000);
3555 const __m128i signedChunk = _mm_add_epi16(chunk, signedBitOffset);
3556 const __m128i offLimitMask = _mm_cmpgt_epi16(signedChunk, thresholdMask);
3559 // replace the non-Latin 1 characters in the chunk with question marks
3560 chunk = _mm_blendv_epi8(chunk, questionMark, offLimitMask);
3562 // offLimitQuestionMark contains '?' for each 16 bits that was off-limit
3563 // the 16 bits that were correct contains zeros
3564 const __m128i offLimitQuestionMark = _mm_and_si128(offLimitMask, questionMark);
3566 // correctBytes contains the bytes that were in limit
3567 // the 16 bits that were off limits contains zeros
3568 const __m128i correctBytes = _mm_andnot_si128(offLimitMask, chunk);
3570 // merge offLimitQuestionMark and correctBytes to have the result
3571 chunk = _mm_or_si128(correctBytes, offLimitQuestionMark);
3578 static QByteArray toLatin1_helper(const QChar *data, int length)
3583 const ushort *src = reinterpret_cast<const ushort *>(data);
3584 uchar *dst = (uchar*) ba.data();
3585 #if defined(QT_ALWAYS_HAVE_SSE2)
3587 const int chunkCount = length >> 4; // divided by 16
3589 for (int i = 0; i < chunkCount; ++i) {
3590 __m128i chunk1 = _mm_loadu_si128((__m128i*)src); // load
3591 chunk1 = mergeQuestionMarks(chunk1);
3594 __m128i chunk2 = _mm_loadu_si128((__m128i*)src); // load
3595 chunk2 = mergeQuestionMarks(chunk2);
3598 // pack the two vector to 16 x 8bits elements
3599 const __m128i result = _mm_packus_epi16(chunk1, chunk2);
3601 _mm_storeu_si128((__m128i*)dst, result); // store
3604 length = length % 16;
3606 #elif defined(QT_ALWAYS_HAVE_NEON)
3607 // Refer to the documentation of the SSE2 implementation
3608 // this use eactly the same method as for SSE except:
3609 // 1) neon has unsigned comparison
3610 // 2) packing is done to 64 bits (8 x 8bits component).
3612 const int chunkCount = length >> 3; // divided by 8
3613 const uint16x8_t questionMark = vdupq_n_u16('?'); // set
3614 const uint16x8_t thresholdMask = vdupq_n_u16(0xff); // set
3615 for (int i = 0; i < chunkCount; ++i) {
3616 uint16x8_t chunk = vld1q_u16((uint16_t *)src); // load
3619 const uint16x8_t offLimitMask = vcgtq_u16(chunk, thresholdMask); // chunk > thresholdMask
3620 const uint16x8_t offLimitQuestionMark = vandq_u16(offLimitMask, questionMark); // offLimitMask & questionMark
3621 const uint16x8_t correctBytes = vbicq_u16(chunk, offLimitMask); // !offLimitMask & chunk
3622 chunk = vorrq_u16(correctBytes, offLimitQuestionMark); // correctBytes | offLimitQuestionMark
3623 const uint8x8_t result = vmovn_u16(chunk); // narrowing move->packing
3624 vst1_u8(dst, result); // store
3627 length = length % 8;
3631 *dst++ = (*src>0xff) ? '?' : (uchar) *src;
3639 Returns a Latin-1 representation of the string as a QByteArray.
3641 The returned byte array is undefined if the string contains non-Latin1
3642 characters. Those characters may be suppressed or replaced with a
3645 \sa fromLatin1(), toAscii(), toUtf8(), toLocal8Bit(), QTextCodec
3647 QByteArray QString::toLatin1() const
3649 return toLatin1_helper(unicode(), length());
3653 Returns an 8-bit representation of the string as a QByteArray.
3655 If a codec has been set using QTextCodec::setCodecForCStrings(),
3656 it is used to convert Unicode to 8-bit char; otherwise this
3657 function does the same as toLatin1().
3659 Note that, despite the name, this function does not necessarily return an US-ASCII
3660 (ANSI X3.4-1986) string and its result may not be US-ASCII compatible.
3662 \sa fromAscii(), toLatin1(), toUtf8(), toLocal8Bit(), QTextCodec
3664 QByteArray QString::toAscii() const
3666 #ifndef QT_NO_TEXTCODEC
3667 if (codecForCStrings)
3668 return codecForCStrings->fromUnicode(*this);
3669 #endif // QT_NO_TEXTCODEC
3673 #if !defined(Q_OS_MAC) && defined(Q_OS_UNIX)
3674 static QByteArray toLocal8Bit_helper(const QChar *data, int length)
3676 #ifndef QT_NO_TEXTCODEC
3677 if (QTextCodec::codecForLocale())
3678 return QTextCodec::codecForLocale()->fromUnicode(data, length);
3679 #endif // QT_NO_TEXTCODEC
3680 return toLatin1_helper(data, length);
3685 Returns the local 8-bit representation of the string as a
3686 QByteArray. The returned byte array is undefined if the string
3687 contains characters not supported by the local 8-bit encoding.
3689 QTextCodec::codecForLocale() is used to perform the conversion from
3690 Unicode. If the locale encoding could not be determined, this function
3691 does the same as toLatin1().
3693 If this string contains any characters that cannot be encoded in the
3694 locale, the returned byte array is undefined. Those characters may be
3695 suppressed or replaced by another.
3697 \sa fromLocal8Bit(), toAscii(), toLatin1(), toUtf8(), QTextCodec
3699 QByteArray QString::toLocal8Bit() const
3701 #ifndef QT_NO_TEXTCODEC
3702 if (QTextCodec::codecForLocale())
3703 return QTextCodec::codecForLocale()->fromUnicode(*this);
3704 #endif // QT_NO_TEXTCODEC
3709 Returns a UTF-8 representation of the string as a QByteArray.
3711 UTF-8 is a Unicode codec and can represent all characters in a Unicode
3712 string like QString.
3714 However, in the Unicode range, there are certain codepoints that are not
3715 considered characters. The Unicode standard reserves the last two
3716 codepoints in each Unicode Plane (U+FFFE, U+FFFF, U+1FFFE, U+1FFFF,
3717 U+2FFFE, etc.), as well as 16 codepoints in the range U+FDD0..U+FDDF,
3718 inclusive, as non-characters. If any of those appear in the string, they
3719 may be discarded and will not appear in the UTF-8 representation, or they
3720 may be replaced by one or more replacement characters.
3722 \sa fromUtf8(), toAscii(), toLatin1(), toLocal8Bit(), QTextCodec
3724 QByteArray QString::toUtf8() const
3727 return QByteArray();
3729 return QUtf8::convertFromUnicode(constData(), length(), 0);
3735 Returns a UCS-4/UTF-32 representation of the string as a QVector<uint>.
3737 UCS-4 is a Unicode codec and is lossless. All characters from this string
3738 can be encoded in UCS-4. The vector is not null terminated.
3740 \sa fromUtf8(), toAscii(), toLatin1(), toLocal8Bit(), QTextCodec, fromUcs4(), toWCharArray()
3742 QVector<uint> QString::toUcs4() const
3744 QVector<uint> v(length());
3746 int len = toUcs4_helper(d->data(), length(), a);
3751 QString::Data *QString::fromLatin1_helper(const char *str, int size)
3755 d = const_cast<Data *>(&shared_null.str);
3756 } else if (size == 0 || (!*str && size < 0)) {
3757 d = const_cast<Data *>(&shared_empty.str);
3760 size = qstrlen(str);
3761 d = static_cast<Data *>(::malloc(sizeof(Data) + (size+1) * sizeof(QChar)));
3765 d->alloc = (uint) size;
3766 d->capacityReserved = false;
3768 d->data()[size] = '\0';
3769 ushort *dst = d->data();
3771 * Unpacking with SSE has been shown to improve performance on recent CPUs
3772 * The same method gives no improvement with NEON.
3774 #if defined(QT_ALWAYS_HAVE_SSE2)
3776 int chunkCount = size >> 4; // divided by 16
3777 const __m128i nullMask = _mm_set1_epi32(0);
3778 for (int i = 0; i < chunkCount; ++i) {
3779 const __m128i chunk = _mm_loadu_si128((__m128i*)str); // load
3782 // unpack the first 8 bytes, padding with zeros
3783 const __m128i firstHalf = _mm_unpacklo_epi8(chunk, nullMask);
3784 _mm_storeu_si128((__m128i*)dst, firstHalf); // store
3787 // unpack the last 8 bytes, padding with zeros
3788 const __m128i secondHalf = _mm_unpackhi_epi8 (chunk, nullMask);
3789 _mm_storeu_si128((__m128i*)dst, secondHalf); // store
3796 *dst++ = (uchar)*str++;
3801 QString::Data *QString::fromAscii_helper(const char *str, int size)
3803 #ifndef QT_NO_TEXTCODEC
3804 if (codecForCStrings) {
3807 d = const_cast<Data *>(&shared_null.str);
3808 } else if (size == 0 || (!*str && size < 0)) {
3809 d = const_cast<Data *>(&shared_empty.str);
3812 size = qstrlen(str);
3813 QString s = codecForCStrings->toUnicode(str, size);
3820 return fromLatin1_helper(str, size);
3823 /*! \fn QString QString::fromLatin1(const char *str, int size)
3824 Returns a QString initialized with the first \a size characters
3825 of the Latin-1 string \a str.
3827 If \a size is -1 (default), it is taken to be strlen(\a
3830 \sa toLatin1(), fromAscii(), fromUtf8(), fromLocal8Bit()
3834 /*! \fn QString QString::fromLocal8Bit(const char *str, int size)
3835 Returns a QString initialized with the first \a size characters
3836 of the 8-bit string \a str.
3838 If \a size is -1 (default), it is taken to be strlen(\a
3841 QTextCodec::codecForLocale() is used to perform the conversion.
3843 \sa toLocal8Bit(), fromAscii(), fromLatin1(), fromUtf8()
3845 QString QString::fromLocal8Bit_helper(const char *str, int size)
3849 if (size == 0 || (!*str && size < 0))
3850 return QString(shared_empty);
3851 #if !defined(QT_NO_TEXTCODEC)
3853 size = qstrlen(str);
3854 QTextCodec *codec = QTextCodec::codecForLocale();
3856 return codec->toUnicode(str, size);
3857 #endif // !QT_NO_TEXTCODEC
3858 return fromLatin1(str, size);
3861 /*! \fn QString QString::fromAscii(const char *, int size);
3862 Returns a QString initialized with the first \a size characters
3863 from the string \a str.
3865 If \a size is -1 (default), it is taken to be strlen(\a
3868 Note that, despite the name, this function actually uses the codec
3869 defined by QTextCodec::setCodecForCStrings() to convert \a str to
3870 Unicode. Depending on the codec, it may not accept valid US-ASCII (ANSI
3871 X3.4-1986) input. If no codec has been set, this function does the same
3874 \sa toAscii(), fromLatin1(), fromUtf8(), fromLocal8Bit()
3877 /*! \fn QString QString::fromUtf8(const char *str, int size)
3878 Returns a QString initialized with the first \a size bytes
3879 of the UTF-8 string \a str.
3881 If \a size is -1 (default), it is taken to be strlen(\a
3884 UTF-8 is a Unicode codec and can represent all characters in a Unicode
3885 string like QString. However, invalid sequences are possible with UTF-8
3886 and, if any such are found, they will be replaced with one or more
3887 "replacement characters", or suppressed. These include non-Unicode
3888 sequences, non-characters, overlong sequences or surrogate codepoints
3891 Non-characters are codepoints that the Unicode standard reserves and must
3892 not be used in text interchange. They are the last two codepoints in each
3893 Unicode Plane (U+FFFE, U+FFFF, U+1FFFE, U+1FFFF, U+2FFFE, etc.), as well
3894 as 16 codepoints in the range U+FDD0..U+FDDF, inclusive.
3896 \sa toUtf8(), fromAscii(), fromLatin1(), fromLocal8Bit()
3898 QString QString::fromUtf8_helper(const char *str, int size)
3903 Q_ASSERT(size != -1);
3904 return QUtf8::convertToUnicode(str, size, 0);
3908 Returns a QString initialized with the first \a size characters
3909 of the Unicode string \a unicode (ISO-10646-UTF-16 encoded).
3911 If \a size is -1 (default), \a unicode must be terminated
3914 This function checks for a Byte Order Mark (BOM). If it is missing,
3915 host byte order is assumed.
3917 This function is slow compared to the other Unicode conversions.
3918 Use QString(const QChar *, int) or QString(const QChar *) if possible.
3920 QString makes a deep copy of the Unicode data.
3922 \sa utf16(), setUtf16()
3924 QString QString::fromUtf16(const ushort *unicode, int size)
3930 while (unicode[size] != 0)
3933 return QUtf16::convertToUnicode((const char *)unicode, size*2, 0);
3940 Returns a QString initialized with the first \a size characters
3941 of the Unicode string \a unicode (ISO-10646-UCS-4 encoded).
3943 If \a size is -1 (default), \a unicode must be terminated
3946 \sa toUcs4(), fromUtf16(), utf16(), setUtf16(), fromWCharArray()
3948 QString QString::fromUcs4(const uint *unicode, int size)
3954 while (unicode[size] != 0)
3957 return QUtf32::convertToUnicode((const char *)unicode, size*4, 0);
3961 Resizes the string to \a size characters and copies \a unicode
3964 If \a unicode is 0, nothing is copied, but the string is still
3967 \sa unicode(), setUtf16()
3969 QString& QString::setUnicode(const QChar *unicode, int size)
3972 if (unicode && size)
3973 memcpy(d->data(), unicode, size * sizeof(QChar));
3978 \fn QString &QString::setUtf16(const ushort *unicode, int size)
3980 Resizes the string to \a size characters and copies \a unicode
3983 If \a unicode is 0, nothing is copied, but the string is still
3986 Note that unlike fromUtf16(), this function does not consider BOMs and
3987 possibly differing byte ordering.
3989 \sa utf16(), setUnicode()
3993 Returns a string that has whitespace removed from the start
3994 and the end, and that has each sequence of internal whitespace
3995 replaced with a single space.
3997 Whitespace means any character for which QChar::isSpace() returns
3998 true. This includes the ASCII characters '\\t', '\\n', '\\v',
3999 '\\f', '\\r', and ' '.
4003 \snippet doc/src/snippets/qstring/main.cpp 57
4007 QString QString::simplified() const
4012 const QChar * const start = reinterpret_cast<QChar *>(d->data());
4013 const QChar *from = start;
4014 const QChar *fromEnd = start + d->size;
4019 if (++from == fromEnd) {
4020 // All-whitespace string
4021 return QString(shared_empty);
4024 // This loop needs no underflow check, as we already determined that
4025 // the string contains non-whitespace. If the string has exactly one
4026 // non-whitespace, it will be checked twice - we can live with that.
4027 while (fromEnd[-1].isSpace())
4029 // The rest of the function depends on the fact that we already know
4030 // that the last character in the source is no whitespace.
4031 const QChar *copyFrom = from;
4034 if (++from == fromEnd) {
4035 // Only leading and/or trailing whitespace, if any at all
4036 return mid(copyFrom - start, from - copyFrom);
4041 if (ch != QLatin1Char(' ')) {
4042 copyCount = from - copyFrom;
4047 copyCount = from - copyFrom - 1;
4051 // 'from' now points at the non-trailing whitespace which made the
4052 // string not simplified in the first place. 'copyCount' is the number
4053 // of already simplified characters - at least one, obviously -
4054 // without a trailing space.
4055 QString result((fromEnd - from) + copyCount, Qt::Uninitialized);
4056 QChar *to = reinterpret_cast<QChar *>(result.d->data());
4057 ::memcpy(to, copyFrom, copyCount * 2);
4062 *to++ = QLatin1Char(' ');
4065 } while (ch.isSpace());
4066 if (from == fromEnd)
4071 if (from == fromEnd)
4073 } while (!ch.isSpace());
4078 result.truncate(to - reinterpret_cast<QChar *>(result.d->data()));
4083 Returns a string that has whitespace removed from the start and
4086 Whitespace means any character for which QChar::isSpace() returns
4087 true. This includes the ASCII characters '\\t', '\\n', '\\v',
4088 '\\f', '\\r', and ' '.
4092 \snippet doc/src/snippets/qstring/main.cpp 82
4094 Unlike simplified(), trimmed() leaves internal whitespace alone.
4098 QString QString::trimmed() const
4102 const QChar *s = (const QChar*)d->data();
4103 if (!s->isSpace() && !s[d->size-1].isSpace())
4106 int end = d->size - 1;
4107 while (start<=end && s[start].isSpace()) // skip white space from start
4109 if (start <= end) { // only white space
4110 while (end && s[end].isSpace()) // skip white space from end
4113 int l = end - start + 1;
4115 return QString(shared_empty);
4117 return QString(s + start, l);
4120 /*! \fn const QChar QString::at(int position) const
4122 Returns the character at the given index \a position in the
4125 The \a position must be a valid index position in the string
4126 (i.e., 0 <= \a position < size()).
4132 \fn QCharRef QString::operator[](int position)
4134 Returns the character at the specified \a position in the string as a
4135 modifiable reference.
4139 \snippet doc/src/snippets/qstring/main.cpp 85
4141 The return value is of type QCharRef, a helper class for QString.
4142 When you get an object of type QCharRef, you can use it as if it
4143 were a QChar &. If you assign to it, the assignment will apply to
4144 the character in the QString from which you got the reference.
4150 \fn const QChar QString::operator[](int position) const
4152 \overload operator[]()
4155 /*! \fn QCharRef QString::operator[](uint position)
4157 \overload operator[]()
4159 Returns the character at the specified \a position in the string as a
4160 modifiable reference. Equivalent to \c at(position).
4163 /*! \fn const QChar QString::operator[](uint position) const
4165 \overload operator[]()
4169 \fn void QString::truncate(int position)
4171 Truncates the string at the given \a position index.
4173 If the specified \a position index is beyond the end of the
4174 string, nothing happens.
4178 \snippet doc/src/snippets/qstring/main.cpp 83
4180 If \a position is negative, it is equivalent to passing zero.
4182 \sa chop(), resize(), left()
4185 void QString::truncate(int pos)
4193 Removes \a n characters from the end of the string.
4195 If \a n is greater than size(), the result is an empty string.
4198 \snippet doc/src/snippets/qstring/main.cpp 15
4200 If you want to remove characters from the \e beginning of the
4201 string, use remove() instead.
4203 \sa truncate(), resize(), remove()
4205 void QString::chop(int n)
4208 resize(d->size - n);
4212 Sets every character in the string to character \a ch. If \a size
4213 is different from -1 (default), the string is resized to \a
4218 \snippet doc/src/snippets/qstring/main.cpp 21
4223 QString& QString::fill(QChar ch, int size)
4225 resize(size < 0 ? d->size : size);
4227 QChar *i = (QChar*)d->data() + d->size;
4228 QChar *b = (QChar*)d->data();
4236 \fn int QString::length() const
4238 Returns the number of characters in this string. Equivalent to
4245 \fn int QString::size() const
4247 Returns the number of characters in this string.
4249 The last character in the string is at position size() - 1. In
4250 addition, QString ensures that the character at position size()
4251 is always '\\0', so that you can use the return value of data()
4252 and constData() as arguments to functions that expect
4253 '\\0'-terminated strings.
4257 \snippet doc/src/snippets/qstring/main.cpp 58
4259 \sa isEmpty(), resize()
4262 /*! \fn bool QString::isNull() const
4264 Returns true if this string is null; otherwise returns false.
4268 \snippet doc/src/snippets/qstring/main.cpp 28
4270 Qt makes a distinction between null strings and empty strings for
4271 historical reasons. For most applications, what matters is
4272 whether or not a string contains any data, and this can be
4273 determined using the isEmpty() function.
4278 /*! \fn bool QString::isEmpty() const
4280 Returns true if the string has no characters; otherwise returns
4285 \snippet doc/src/snippets/qstring/main.cpp 27
4290 /*! \fn QString &QString::operator+=(const QString &other)
4292 Appends the string \a other onto the end of this string and
4293 returns a reference to this string.
4297 \snippet doc/src/snippets/qstring/main.cpp 84
4299 This operation is typically very fast (\l{constant time}),
4300 because QString preallocates extra space at the end of the string
4301 data so it can grow without reallocating the entire string each
4304 \sa append(), prepend()
4307 /*! \fn QString &QString::operator+=(const QLatin1String &str)
4309 \overload operator+=()
4311 Appends the Latin-1 string \a str to this string.
4314 /*! \fn QString &QString::operator+=(const QByteArray &ba)
4316 \overload operator+=()
4318 Appends the byte array \a ba to this string. The byte array is converted
4319 to Unicode using the fromAscii() function. If any NUL characters ('\0')
4320 are embedded in the \a ba byte array, they will be included in the
4323 You can disable this function by defining \c
4324 QT_NO_CAST_FROM_ASCII when you compile your applications. This
4325 can be useful if you want to ensure that all user-visible strings
4326 go through QObject::tr(), for example.
4329 /*! \fn QString &QString::operator+=(const char *str)
4331 \overload operator+=()
4333 Appends the string \a str to this string. The const char pointer
4334 is converted to Unicode using the fromAscii() function.
4336 You can disable this function by defining \c QT_NO_CAST_FROM_ASCII
4337 when you compile your applications. This can be useful if you want
4338 to ensure that all user-visible strings go through QObject::tr(),
4342 /*! \fn QString &QString::operator+=(const QStringRef &str)
4344 \overload operator+=()
4346 Appends the string section referenced by \a str to this string.
4349 /*! \fn QString &QString::operator+=(char ch)
4351 \overload operator+=()
4353 Appends the character \a ch to this string. The character is
4354 converted to Unicode using the fromAscii() function.
4356 You can disable this function by defining \c QT_NO_CAST_FROM_ASCII
4357 when you compile your applications. This can be useful if you want
4358 to ensure that all user-visible strings go through QObject::tr(),
4362 /*! \fn QString &QString::operator+=(QChar ch)
4364 \overload operator+=()
4366 Appends the character \a ch to the string.
4369 /*! \fn QString &QString::operator+=(QChar::SpecialCharacter c)
4371 \overload operator+=()
4377 \fn bool operator==(const char *s1, const QString &s2)
4379 \overload operator==()
4382 Returns true if \a s1 is equal to \a s2; otherwise returns false.
4383 Note that no string is equal to \a s1 being 0.
4385 Equivalent to \c {s1 != 0 && compare(s1, s2) == 0}.
4387 \sa QString::compare()
4391 \fn bool operator!=(const char *s1, const QString &s2)
4394 Returns true if \a s1 is not equal to \a s2; otherwise returns
4397 For \a s1 != 0, this is equivalent to \c {compare(} \a s1, \a s2
4398 \c {) != 0}. Note that no string is equal to \a s1 being 0.
4400 \sa QString::compare()
4404 \fn bool operator<(const char *s1, const QString &s2)
4407 Returns true if \a s1 is lexically less than \a s2; otherwise
4408 returns false. For \a s1 != 0, this is equivalent to \c
4409 {compare(s1, s2) < 0}.
4411 The comparison is based exclusively on the numeric Unicode values
4412 of the characters and is very fast, but is not what a human would
4413 expect. Consider sorting user-interface strings using the
4414 QString::localeAwareCompare() function.
4416 \sa QString::compare()
4420 \fn bool operator<=(const char *s1, const QString &s2)
4423 Returns true if \a s1 is lexically less than or equal to \a s2;
4424 otherwise returns false. For \a s1 != 0, this is equivalent to \c
4425 {compare(s1, s2) <= 0}.
4427 The comparison is based exclusively on the numeric Unicode values
4428 of the characters and is very fast, but is not what a human would
4429 expect. Consider sorting user-interface strings with
4430 QString::localeAwareCompare().
4432 \sa QString::compare()
4436 \fn bool operator>(const char *s1, const QString &s2)
4439 Returns true if \a s1 is lexically greater than \a s2; otherwise
4440 returns false. Equivalent to \c {compare(s1, s2) > 0}.
4442 The comparison is based exclusively on the numeric Unicode values
4443 of the characters and is very fast, but is not what a human would
4444 expect. Consider sorting user-interface strings using the
4445 QString::localeAwareCompare() function.
4447 \sa QString::compare()
4451 \fn bool operator>=(const char *s1, const QString &s2)
4454 Returns true if \a s1 is lexically greater than or equal to \a s2;
4455 otherwise returns false. For \a s1 != 0, this is equivalent to \c
4456 {compare(s1, s2) >= 0}.
4458 The comparison is based exclusively on the numeric Unicode values
4459 of the characters and is very fast, but is not what a human would
4460 expect. Consider sorting user-interface strings using the
4461 QString::localeAwareCompare() function.
4465 \fn const QString operator+(const QString &s1, const QString &s2)
4468 Returns a string which is the result of concatenating \a s1 and \a
4473 \fn const QString operator+(const QString &s1, const char *s2)
4476 Returns a string which is the result of concatenating \a s1 and \a
4477 s2 (\a s2 is converted to Unicode using the QString::fromAscii()
4480 \sa QString::fromAscii()
4484 \fn const QString operator+(const char *s1, const QString &s2)
4487 Returns a string which is the result of concatenating \a s1 and \a
4488 s2 (\a s1 is converted to Unicode using the QString::fromAscii()
4491 \sa QString::fromAscii()
4495 \fn const QString operator+(const QString &s, char ch)
4498 Returns a string which is the result of concatenating the string
4499 \a s and the character \a ch.
4503 \fn const QString operator+(char ch, const QString &s)
4506 Returns a string which is the result of concatenating the
4507 character \a ch and the string \a s.
4511 \fn int QString::compare(const QString &s1, const QString &s2, Qt::CaseSensitivity cs)
4514 Compares \a s1 with \a s2 and returns an integer less than, equal
4515 to, or greater than zero if \a s1 is less than, equal to, or
4518 If \a cs is Qt::CaseSensitive, the comparison is case sensitive;
4519 otherwise the comparison is case insensitive.
4521 Case sensitive comparison is based exclusively on the numeric
4522 Unicode values of the characters and is very fast, but is not what
4523 a human would expect. Consider sorting user-visible strings with
4524 localeAwareCompare().
4526 \snippet doc/src/snippets/qstring/main.cpp 16
4528 \sa operator==(), operator<(), operator>()
4532 \fn int QString::compare(const QString &s1, const QLatin1String &s2, Qt::CaseSensitivity cs)
4536 Performs a comparison of \a s1 and \a s2, using the case
4537 sensitivity setting \a cs.
4541 \fn int QString::compare(const QLatin1String &s1, const QString &s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
4546 Performs a comparison of \a s1 and \a s2, using the case
4547 sensitivity setting \a cs.
4555 Lexically compares this string with the \a other string and
4556 returns an integer less than, equal to, or greater than zero if
4557 this string is less than, equal to, or greater than the other
4560 Same as compare(*this, \a other, \a cs).
4562 int QString::compare(const QString &other, Qt::CaseSensitivity cs) const
4564 if (cs == Qt::CaseSensitive)
4565 return ucstrcmp(constData(), length(), other.constData(), other.length());
4566 return ucstricmp(d->data(), d->data() + d->size, other.d->data(), other.d->data() + other.d->size);
4573 int QString::compare_helper(const QChar *data1, int length1, const QChar *data2, int length2,
4574 Qt::CaseSensitivity cs)
4576 if (cs == Qt::CaseSensitive)
4577 return ucstrcmp(data1, length1, data2, length2);
4578 register const ushort *s1 = reinterpret_cast<const ushort *>(data1);
4579 register const ushort *s2 = reinterpret_cast<const ushort *>(data2);
4580 return ucstricmp(s1, s1 + length1, s2, s2 + length2);
4587 Same as compare(*this, \a other, \a cs).
4589 int QString::compare(const QLatin1String &other, Qt::CaseSensitivity cs) const
4591 return compare_helper(unicode(), length(), other, cs);
4595 \fn int QString::compare(const QStringRef &ref, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
4598 Compares the string reference, \a ref, with the string and returns
4599 an integer less than, equal to, or greater than zero if the string
4600 is less than, equal to, or greater than \a ref.
4604 \fn int QString::compare(const QString &s1, const QStringRef &s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
4612 int QString::compare_helper(const QChar *data1, int length1, QLatin1String s2,
4613 Qt::CaseSensitivity cs)
4615 const ushort *uc = reinterpret_cast<const ushort *>(data1);
4616 const ushort *uce = uc + length1;
4617 const uchar *c = (uchar *)s2.latin1();
4622 if (cs == Qt::CaseSensitive) {
4623 const ushort *e = uc + length1;
4624 if (s2.size() < length1)
4627 int diff = *uc - *c;
4634 if (c == (const uchar *)s2.latin1() + s2.size())
4640 return ucstricmp(uc, uce, c, c + s2.size());
4645 \fn int QString::localeAwareCompare(const QString & s1, const QString & s2)
4647 Compares \a s1 with \a s2 and returns an integer less than, equal
4648 to, or greater than zero if \a s1 is less than, equal to, or
4651 The comparison is performed in a locale- and also
4652 platform-dependent manner. Use this function to present sorted
4653 lists of strings to the user.
4655 On Mac OS X since Qt 4.3, this function compares according the
4656 "Order for sorted lists" setting in the International prefereces panel.
4658 \sa compare(), QTextCodec::locale()
4662 \fn int QString::localeAwareCompare(const QStringRef &other) const
4664 \overload localeAwareCompare()
4666 Compares this string with the \a other string and returns an
4667 integer less than, equal to, or greater than zero if this string
4668 is less than, equal to, or greater than the \a other string.
4670 The comparison is performed in a locale- and also
4671 platform-dependent manner. Use this function to present sorted
4672 lists of strings to the user.
4674 Same as \c {localeAwareCompare(*this, other)}.
4678 \fn int QString::localeAwareCompare(const QString &s1, const QStringRef &s2)
4680 \overload localeAwareCompare()
4682 Compares \a s1 with \a s2 and returns an integer less than, equal
4683 to, or greater than zero if \a s1 is less than, equal to, or
4686 The comparison is performed in a locale- and also
4687 platform-dependent manner. Use this function to present sorted
4688 lists of strings to the user.
4692 #if !defined(CSTR_LESS_THAN)
4693 #define CSTR_LESS_THAN 1
4694 #define CSTR_EQUAL 2
4695 #define CSTR_GREATER_THAN 3
4699 \overload localeAwareCompare()
4701 Compares this string with the \a other string and returns an
4702 integer less than, equal to, or greater than zero if this string
4703 is less than, equal to, or greater than the \a other string.
4705 The comparison is performed in a locale- and also
4706 platform-dependent manner. Use this function to present sorted
4707 lists of strings to the user.
4709 Same as \c {localeAwareCompare(*this, other)}.
4711 int QString::localeAwareCompare(const QString &other) const
4713 return localeAwareCompare_helper(constData(), length(), other.constData(), other.length());
4720 int QString::localeAwareCompare_helper(const QChar *data1, int length1,
4721 const QChar *data2, int length2)
4723 // do the right thing for null and empty
4724 if (length1 == 0 || length2 == 0)
4725 return ucstrcmp(data1, length1, data2, length2);
4727 #if defined(Q_OS_WIN32) || defined(Q_OS_WINCE)
4728 int res = CompareString(GetUserDefaultLCID(), 0, (wchar_t*)data1, length1, (wchar_t*)data2, length2);
4731 case CSTR_LESS_THAN:
4733 case CSTR_GREATER_THAN:
4738 #elif defined (Q_OS_MAC)
4739 // Use CFStringCompare for comparing strings on Mac. This makes Qt order
4740 // strings the same way as native applications do, and also respects
4741 // the "Order for sorted lists" setting in the International preferences
4743 const CFStringRef thisString =
4744 CFStringCreateWithCharactersNoCopy(kCFAllocatorDefault,
4745 reinterpret_cast<const UniChar *>(data1), length1, kCFAllocatorNull);
4746 const CFStringRef otherString =
4747 CFStringCreateWithCharactersNoCopy(kCFAllocatorDefault,
4748 reinterpret_cast<const UniChar *>(data2), length2, kCFAllocatorNull);
4750 const int result = CFStringCompare(thisString, otherString, kCFCompareLocalized);
4751 CFRelease(thisString);
4752 CFRelease(otherString);
4754 #elif defined(Q_OS_UNIX)
4755 # if defined(QT_USE_ICU)
4757 if (qt_ucol_strcoll(data1, length1, data2, length2, &res)) {
4759 res = ucstrcmp(data1, length1, data2, length2);
4761 } // else fall through
4763 // declared in <string.h>
4764 int delta = strcoll(toLocal8Bit_helper(data1, length1), toLocal8Bit_helper(data2, length2));
4766 delta = ucstrcmp(data1, length1, data2, length2);
4769 return ucstrcmp(data1, length1, data2, length2);
4775 \fn const QChar *QString::unicode() const
4777 Returns a '\\0'-terminated Unicode representation of the string.
4778 The result remains valid until the string is modified.
4784 \fn const ushort *QString::utf16() const
4786 Returns the QString as a '\\0\'-terminated array of unsigned
4787 shorts. The result remains valid until the string is modified.
4789 The returned string is in host byte order.
4794 const ushort *QString::utf16() const
4797 const_cast<QString*>(this)->realloc(); // ensure '\\0'-termination for ::fromRawData strings
4802 Returns a string of size \a width that contains this string
4803 padded by the \a fill character.
4805 If \a truncate is false and the size() of the string is more than
4806 \a width, then the returned string is a copy of the string.
4808 \snippet doc/src/snippets/qstring/main.cpp 32
4810 If \a truncate is true and the size() of the string is more than
4811 \a width, then any characters in a copy of the string after
4812 position \a width are removed, and the copy is returned.
4814 \snippet doc/src/snippets/qstring/main.cpp 33
4816 \sa rightJustified()
4819 QString QString::leftJustified(int width, QChar fill, bool truncate) const
4823 int padlen = width - len;
4825 result.resize(len+padlen);
4827 memcpy(result.d->data(), d->data(), sizeof(QChar)*len);
4828 QChar *uc = (QChar*)result.d->data() + len;
4833 result = left(width);
4841 Returns a string of size() \a width that contains the \a fill
4842 character followed by the string. For example:
4844 \snippet doc/src/snippets/qstring/main.cpp 49
4846 If \a truncate is false and the size() of the string is more than
4847 \a width, then the returned string is a copy of the string.
4849 If \a truncate is true and the size() of the string is more than
4850 \a width, then the resulting string is truncated at position \a
4853 \snippet doc/src/snippets/qstring/main.cpp 50
4858 QString QString::rightJustified(int width, QChar fill, bool truncate) const
4862 int padlen = width - len;
4864 result.resize(len+padlen);
4865 QChar *uc = (QChar*)result.d->data();
4869 memcpy(uc, d->data(), sizeof(QChar)*len);
4872 result = left(width);
4880 Returns a lowercase copy of the string.
4882 \snippet doc/src/snippets/qstring/main.cpp 75
4884 The case conversion will always happen in the 'C' locale. For locale dependent
4885 case folding use QLocale::toLower()
4887 \sa toUpper(), QLocale::toLower()
4890 QString QString::toLower() const
4892 const ushort *p = d->data();
4896 const ushort *e = p + d->size;
4897 // this avoids out of bounds check in the loop
4898 while (e != p && QChar::isHighSurrogate(*(e - 1)))
4901 const QUnicodeTables::Properties *prop;
4903 if (QChar::isHighSurrogate(*p) && QChar::isLowSurrogate(p[1])) {
4905 prop = qGetProp(QChar::surrogateToUcs4(high, *p));
4907 prop = qGetProp(*p);
4909 if (prop->lowerCaseDiff) {
4910 if (QChar::isLowSurrogate(*p))
4911 --p; // safe; diff is 0 for surrogates
4912 QString s(d->size, Qt::Uninitialized);
4913 memcpy(s.d->data(), d->data(), (p - d->data())*sizeof(ushort));
4914 ushort *pp = s.d->data() + (p - d->data());
4916 if (QChar::isHighSurrogate(*p) && QChar::isLowSurrogate(p[1])) {
4918 prop = qGetProp(QChar::surrogateToUcs4(*pp++, *p));
4920 prop = qGetProp(*p);
4922 if (prop->lowerCaseSpecial) {
4923 const ushort *specialCase = specialCaseMap + prop->lowerCaseDiff;
4924 ushort length = *specialCase++;
4925 int pos = pp - s.d->data();
4926 s.resize(s.d->size + length - 1);
4927 pp = s.d->data() + pos;
4929 *pp++ = *specialCase++;
4931 *pp++ = *p + prop->lowerCaseDiff;
4936 // this restores high surrogate parts eaten above, if any
4937 while (e != d->data() + d->size)
4948 Returns the case folded equivalent of the string. For most Unicode
4949 characters this is the same as toLower().
4951 QString QString::toCaseFolded() const
4953 const ushort *p = d->data();
4957 const ushort *e = p + d->size;
4958 // this avoids out of bounds check in the loop
4959 while (e != p && QChar::isHighSurrogate(*(e - 1)))
4962 const QUnicodeTables::Properties *prop;
4964 if (QChar::isHighSurrogate(*p) && QChar::isLowSurrogate(p[1])) {
4966 prop = qGetProp(QChar::surrogateToUcs4(high, *p));
4968 prop = qGetProp(*p);
4970 if (prop->caseFoldDiff) {
4971 if (QChar::isLowSurrogate(*p))
4972 --p; // safe; diff is 0 for surrogates
4973 QString s(d->size, Qt::Uninitialized);
4974 memcpy(s.d->data(), d->data(), (p - d->data())*sizeof(ushort));
4975 ushort *pp = s.d->data() + (p - d->data());
4977 if (QChar::isHighSurrogate(*p) && QChar::isLowSurrogate(p[1])) {
4979 prop = qGetProp(QChar::surrogateToUcs4(*pp++, *p));
4981 prop = qGetProp(*p);
4983 if (prop->caseFoldSpecial) {
4984 //### we currently don't support full case foldings
4986 *pp++ = *p + prop->caseFoldDiff;
4991 // this restores high surrogate parts eaten above, if any
4992 while (e != d->data() + d->size)
5003 Returns an uppercase copy of the string.
5005 \snippet doc/src/snippets/qstring/main.cpp 81
5007 The case conversion will always happen in the 'C' locale. For locale dependent
5008 case folding use QLocale::toUpper()
5010 \sa toLower(), QLocale::toLower()
5012 QString QString::toUpper() const
5014 const ushort *p = d->data();
5018 const ushort *e = p + d->size;
5019 // this avoids out of bounds check in the loop
5020 while (e != p && QChar::isHighSurrogate(*(e - 1)))
5023 const QUnicodeTables::Properties *prop;
5025 if (QChar::isHighSurrogate(*p) && QChar::isLowSurrogate(p[1])) {
5027 prop = qGetProp(QChar::surrogateToUcs4(high, *p));
5029 prop = qGetProp(*p);
5031 if (prop->upperCaseDiff) {
5032 if (QChar::isLowSurrogate(*p))
5033 --p; // safe; diff is 0 for surrogates
5034 QString s(d->size, Qt::Uninitialized);
5035 memcpy(s.d->data(), d->data(), (p - d->data())*sizeof(ushort));
5036 ushort *pp = s.d->data() + (p - d->data());
5038 if (QChar::isHighSurrogate(*p) && QChar::isLowSurrogate(p[1])) {
5040 prop = qGetProp(QChar::surrogateToUcs4(*pp++, *p));
5042 prop = qGetProp(*p);
5044 if (prop->upperCaseSpecial) {
5045 const ushort *specialCase = specialCaseMap + prop->upperCaseDiff;
5046 ushort length = *specialCase++;
5047 int pos = pp - s.d->data();
5048 s.resize(s.d->size + length - 1);
5049 pp = s.d->data() + pos;
5051 *pp++ = *specialCase++;
5053 *pp++ = *p + prop->upperCaseDiff;
5058 // this restores high surrogate parts eaten above, if any
5059 while (e != d->data() + d->size)
5069 // ### Qt 5: Consider whether this function shouldn't be removed See task 202871.
5071 Safely builds a formatted string from the format string \a cformat
5072 and an arbitrary list of arguments.
5074 The %lc escape sequence expects a unicode character of type ushort
5075 (as returned by QChar::unicode()). The %ls escape sequence expects
5076 a pointer to a zero-terminated array of unicode characters of type
5077 ushort (as returned by QString::utf16()).
5079 \note This function expects a UTF-8 string for %s and Latin-1 for
5082 The format string supports most of the conversion specifiers
5083 provided by printf() in the standard C++ library. It doesn't
5084 honor the length modifiers (e.g. \c h for \c short, \c ll for
5085 \c{long long}). If you need those, use the standard snprintf()
5088 \snippet doc/src/snippets/qstring/main.cpp 63
5090 \warning We do not recommend using QString::sprintf() in new Qt
5091 code. Instead, consider using QTextStream or arg(), both of
5092 which support Unicode strings seamlessly and are type-safe.
5093 Here's an example that uses QTextStream:
5095 \snippet doc/src/snippets/qstring/main.cpp 64
5097 For \l {QObject::tr()}{translations}, especially if the strings
5098 contains more than one escape sequence, you should consider using
5099 the arg() function instead. This allows the order of the
5100 replacements to be controlled by the translator.
5105 QString &QString::sprintf(const char *cformat, ...)
5108 va_start(ap, cformat);
5109 QString &s = vsprintf(cformat, ap);
5115 Equivalent method to sprintf(), but takes a va_list \a ap
5116 instead a list of variable arguments. See the sprintf()
5117 documentation for an explanation of \a cformat.
5119 This method does not call the va_end macro, the caller
5120 is responsible to call va_end on \a ap.
5125 QString &QString::vsprintf(const char* cformat, va_list ap)
5127 QLocale locale(QLocale::C);
5129 if (!cformat || !*cformat) {
5131 *this = fromLatin1("");
5138 const char *c = cformat;
5140 // Copy non-escape chars to result
5141 #ifndef QT_NO_TEXTCODEC
5143 while (*(c + i) != '\0' && *(c + i) != '%')
5145 if (codecForCStrings)
5146 result.append(codecForCStrings->toUnicode(c, i));
5148 result.append(fromLatin1(c, i));
5151 while (*c != '\0' && *c != '%')
5152 result.append(QLatin1Char(*c++));
5159 const char *escape_start = c;
5163 result.append(QLatin1Char('%')); // a % at the end of the string - treat as non-escape text
5167 result.append(QLatin1Char('%')); // %%
5172 // Parse flag characters
5174 bool no_more_flags = false;
5177 case '#': flags |= QLocalePrivate::Alternate; break;
5178 case '0': flags |= QLocalePrivate::ZeroPadded; break;
5179 case '-': flags |= QLocalePrivate::LeftAdjusted; break;
5180 case ' ': flags |= QLocalePrivate::BlankBeforePositive; break;
5181 case '+': flags |= QLocalePrivate::AlwaysShowSign; break;
5182 case '\'': flags |= QLocalePrivate::ThousandsGroup; break;
5183 default: no_more_flags = true; break;
5188 } while (!no_more_flags);
5191 result.append(QLatin1String(escape_start)); // incomplete escape, treat as non-escape text
5195 // Parse field width
5196 int width = -1; // -1 means unspecified
5199 while (*c != '\0' && qIsDigit(*c))
5200 width_str.append(QLatin1Char(*c++));
5202 // can't be negative - started with a digit
5203 // contains at least one digit
5204 width = width_str.toInt();
5206 else if (*c == '*') {
5207 width = va_arg(ap, int);
5209 width = -1; // treat all negative numbers as unspecified
5214 result.append(QLatin1String(escape_start)); // incomplete escape, treat as non-escape text
5219 int precision = -1; // -1 means unspecified
5223 QString precision_str;
5224 while (*c != '\0' && qIsDigit(*c))
5225 precision_str.append(QLatin1Char(*c++));
5227 // can't be negative - started with a digit
5228 // contains at least one digit
5229 precision = precision_str.toInt();
5231 else if (*c == '*') {
5232 precision = va_arg(ap, int);
5234 precision = -1; // treat all negative numbers as unspecified
5240 result.append(QLatin1String(escape_start)); // incomplete escape, treat as non-escape text
5244 // Parse the length modifier
5245 enum LengthMod { lm_none, lm_hh, lm_h, lm_l, lm_ll, lm_L, lm_j, lm_z, lm_t };
5246 LengthMod length_mod = lm_none;
5293 result.append(QLatin1String(escape_start)); // incomplete escape, treat as non-escape text
5297 // Parse the conversion specifier and do the conversion
5303 switch (length_mod) {
5304 case lm_none: i = va_arg(ap, int); break;
5305 case lm_hh: i = va_arg(ap, int); break;
5306 case lm_h: i = va_arg(ap, int); break;
5307 case lm_l: i = va_arg(ap, long int); break;
5308 case lm_ll: i = va_arg(ap, qint64); break;
5309 case lm_j: i = va_arg(ap, long int); break;
5310 case lm_z: i = va_arg(ap, size_t); break;
5311 case lm_t: i = va_arg(ap, int); break;
5312 default: i = 0; break;
5314 subst = locale.d()->longLongToString(i, precision, 10, width, flags);
5323 switch (length_mod) {
5324 case lm_none: u = va_arg(ap, uint); break;
5325 case lm_hh: u = va_arg(ap, uint); break;
5326 case lm_h: u = va_arg(ap, uint); break;
5327 case lm_l: u = va_arg(ap, ulong); break;
5328 case lm_ll: u = va_arg(ap, quint64); break;
5329 case lm_z: u = va_arg(ap, size_t); break;
5330 default: u = 0; break;
5334 flags |= QLocalePrivate::CapitalEorX;
5337 switch (qToLower(*c)) {
5346 subst = locale.d()->unsLongLongToString(u, precision, base, width, flags);
5359 if (length_mod == lm_L)
5360 d = va_arg(ap, long double); // not supported - converted to a double
5362 d = va_arg(ap, double);
5365 flags |= QLocalePrivate::CapitalEorX;
5367 QLocalePrivate::DoubleForm form = QLocalePrivate::DFDecimal;
5368 switch (qToLower(*c)) {
5369 case 'e': form = QLocalePrivate::DFExponent; break;
5370 case 'a': // not supported - decimal form used instead
5371 case 'f': form = QLocalePrivate::DFDecimal; break;
5372 case 'g': form = QLocalePrivate::DFSignificantDigits; break;
5375 subst = locale.d()->doubleToString(d, precision, form, width, flags);
5380 if (length_mod == lm_l)
5381 subst = QChar((ushort) va_arg(ap, int));
5383 subst = QLatin1Char((uchar) va_arg(ap, int));
5388 if (length_mod == lm_l) {
5389 const ushort *buff = va_arg(ap, const ushort*);
5390 const ushort *ch = buff;
5393 subst.setUtf16(buff, ch - buff);
5395 subst = QString::fromUtf8(va_arg(ap, const char*));
5396 if (precision != -1)
5397 subst.truncate(precision);
5402 void *arg = va_arg(ap, void*);
5404 quint64 i = reinterpret_cast<quint64>(arg);
5406 quint64 i = reinterpret_cast<unsigned long>(arg);
5408 flags |= QLocalePrivate::Alternate;
5409 subst = locale.d()->unsLongLongToString(i, precision, 16, width, flags);
5414 switch (length_mod) {
5416 signed char *n = va_arg(ap, signed char*);
5417 *n = result.length();
5421 short int *n = va_arg(ap, short int*);
5422 *n = result.length();
5426 long int *n = va_arg(ap, long int*);
5427 *n = result.length();
5431 qint64 *n = va_arg(ap, qint64*);
5432 volatile uint tmp = result.length(); // egcs-2.91.66 gets internal
5433 *n = tmp; // compiler error without volatile
5437 int *n = va_arg(ap, int*);
5438 *n = result.length();
5445 default: // bad escape, treat as non-escape text
5446 for (const char *cc = escape_start; cc != c; ++cc)
5447 result.append(QLatin1Char(*cc));
5451 if (flags & QLocalePrivate::LeftAdjusted)
5452 result.append(subst.leftJustified(width));
5454 result.append(subst.rightJustified(width));
5463 Returns the string converted to a \c{long long} using base \a
5464 base, which is 10 by default and must be between 2 and 36, or 0.
5465 Returns 0 if the conversion fails.
5467 If a conversion error occurs, *\a{ok} is set to false; otherwise
5468 *\a{ok} is set to true.
5470 If \a base is 0, the C language convention is used: If the string
5471 begins with "0x", base 16 is used; if the string begins with "0",
5472 base 8 is used; otherwise, base 10 is used.
5474 The string conversion will always happen in the 'C' locale. For locale
5475 dependent conversion use QLocale::toLongLong()
5479 \snippet doc/src/snippets/qstring/main.cpp 74
5481 \sa number(), toULongLong(), toInt(), QLocale::toLongLong()
5484 qint64 QString::toLongLong(bool *ok, int base) const
5486 #if defined(QT_CHECK_RANGE)
5487 if (base != 0 && (base < 2 || base > 36)) {
5488 qWarning("QString::toLongLong: Invalid base (%d)", base);
5493 QLocale c_locale(QLocale::C);
5494 return c_locale.d()->stringToLongLong(*this, base, ok, QLocalePrivate::FailOnGroupSeparators);
5498 Returns the string converted to an \c{unsigned long long} using base \a
5499 base, which is 10 by default and must be between 2 and 36, or 0.
5500 Returns 0 if the conversion fails.
5502 If a conversion error occurs, *\a{ok} is set to false; otherwise
5503 *\a{ok} is set to true.
5505 If \a base is 0, the C language convention is used: If the string
5506 begins with "0x", base 16 is used; if the string begins with "0",
5507 base 8 is used; otherwise, base 10 is used.
5509 The string conversion will always happen in the 'C' locale. For locale
5510 dependent conversion use QLocale::toULongLong()
5514 \snippet doc/src/snippets/qstring/main.cpp 79
5516 \sa number(), toLongLong(), QLocale::toULongLong()
5519 quint64 QString::toULongLong(bool *ok, int base) const
5521 #if defined(QT_CHECK_RANGE)
5522 if (base != 0 && (base < 2 || base > 36)) {
5523 qWarning("QString::toULongLong: Invalid base (%d)", base);
5528 QLocale c_locale(QLocale::C);
5529 return c_locale.d()->stringToUnsLongLong(*this, base, ok, QLocalePrivate::FailOnGroupSeparators);
5533 \fn long QString::toLong(bool *ok, int base) const
5535 Returns the string converted to a \c long using base \a
5536 base, which is 10 by default and must be between 2 and 36, or 0.
5537 Returns 0 if the conversion fails.
5539 If a conversion error occurs, *\a{ok} is set to false; otherwise
5540 *\a{ok} is set to true.
5542 If \a base is 0, the C language convention is used: If the string
5543 begins with "0x", base 16 is used; if the string begins with "0",
5544 base 8 is used; otherwise, base 10 is used.
5546 The string conversion will always happen in the 'C' locale. For locale
5547 dependent conversion use QLocale::toLong()
5551 \snippet doc/src/snippets/qstring/main.cpp 73
5553 \sa number(), toULong(), toInt(), QLocale::toLong()
5556 long QString::toLong(bool *ok, int base) const
5558 qint64 v = toLongLong(ok, base);
5559 if (v < LONG_MIN || v > LONG_MAX) {
5568 \fn ulong QString::toULong(bool *ok, int base) const
5570 Returns the string converted to an \c{unsigned long} using base \a
5571 base, which is 10 by default and must be between 2 and 36, or 0.
5572 Returns 0 if the conversion fails.
5574 If a conversion error occurs, *\a{ok} is set to false; otherwise
5575 *\a{ok} is set to true.
5577 If \a base is 0, the C language convention is used: If the string
5578 begins with "0x", base 16 is used; if the string begins with "0",
5579 base 8 is used; otherwise, base 10 is used.
5581 The string conversion will always happen in the 'C' locale. For locale
5582 dependent conversion use QLocale::toULong()
5586 \snippet doc/src/snippets/qstring/main.cpp 78
5588 \sa number(), QLocale::toULong()
5591 ulong QString::toULong(bool *ok, int base) const
5593 quint64 v = toULongLong(ok, base);
5594 if (v > ULONG_MAX) {
5604 Returns the string converted to an \c int using base \a
5605 base, which is 10 by default and must be between 2 and 36, or 0.
5606 Returns 0 if the conversion fails.
5608 If a conversion error occurs, *\a{ok} is set to false; otherwise
5609 *\a{ok} is set to true.
5611 If \a base is 0, the C language convention is used: If the string
5612 begins with "0x", base 16 is used; if the string begins with "0",
5613 base 8 is used; otherwise, base 10 is used.
5615 The string conversion will always happen in the 'C' locale. For locale
5616 dependent conversion use QLocale::toInt()
5620 \snippet doc/src/snippets/qstring/main.cpp 72
5622 \sa number(), toUInt(), toDouble(), QLocale::toInt()
5625 int QString::toInt(bool *ok, int base) const
5627 qint64 v = toLongLong(ok, base);
5628 if (v < INT_MIN || v > INT_MAX) {
5637 Returns the string converted to an \c{unsigned int} using base \a
5638 base, which is 10 by default and must be between 2 and 36, or 0.
5639 Returns 0 if the conversion fails.
5641 If a conversion error occurs, *\a{ok} is set to false; otherwise
5642 *\a{ok} is set to true.
5644 If \a base is 0, the C language convention is used: If the string
5645 begins with "0x", base 16 is used; if the string begins with "0",
5646 base 8 is used; otherwise, base 10 is used.
5648 The string conversion will always happen in the 'C' locale. For locale
5649 dependent conversion use QLocale::toUInt()
5653 \snippet doc/src/snippets/qstring/main.cpp 77
5655 \sa number(), toInt(), QLocale::toUInt()
5658 uint QString::toUInt(bool *ok, int base) const
5660 quint64 v = toULongLong(ok, base);
5670 Returns the string converted to a \c short using base \a
5671 base, which is 10 by default and must be between 2 and 36, or 0.
5672 Returns 0 if the conversion fails.
5674 If a conversion error occurs, *\a{ok} is set to false; otherwise
5675 *\a{ok} is set to true.
5677 If \a base is 0, the C language convention is used: If the string
5678 begins with "0x", base 16 is used; if the string begins with "0",
5679 base 8 is used; otherwise, base 10 is used.
5681 The string conversion will always happen in the 'C' locale. For locale
5682 dependent conversion use QLocale::toShort()
5686 \snippet doc/src/snippets/qstring/main.cpp 76
5688 \sa number(), toUShort(), toInt(), QLocale::toShort()
5691 short QString::toShort(bool *ok, int base) const
5693 long v = toLongLong(ok, base);
5694 if (v < SHRT_MIN || v > SHRT_MAX) {
5703 Returns the string converted to an \c{unsigned short} using base \a
5704 base, which is 10 by default and must be between 2 and 36, or 0.
5705 Returns 0 if the conversion fails.
5707 If a conversion error occurs, *\a{ok} is set to false; otherwise
5708 *\a{ok} is set to true.
5710 If \a base is 0, the C language convention is used: If the string
5711 begins with "0x", base 16 is used; if the string begins with "0",
5712 base 8 is used; otherwise, base 10 is used.
5714 The string conversion will always happen in the 'C' locale. For locale
5715 dependent conversion use QLocale::toUShort()
5719 \snippet doc/src/snippets/qstring/main.cpp 80
5721 \sa number(), toShort(), QLocale::toUShort()
5724 ushort QString::toUShort(bool *ok, int base) const
5726 ulong v = toULongLong(ok, base);
5727 if (v > USHRT_MAX) {
5737 Returns the string converted to a \c double value.
5739 Returns 0.0 if the conversion fails.
5741 If a conversion error occurs, \c{*}\a{ok} is set to false;
5742 otherwise \c{*}\a{ok} is set to true.
5744 \snippet doc/src/snippets/qstring/main.cpp 66
5746 Various string formats for floating point numbers can be converted
5749 \snippet doc/src/snippets/qstring/main.cpp 67
5751 The string conversion will always happen in the 'C' locale. For locale
5752 dependent conversion use QLocale::toDouble()
5754 \snippet doc/src/snippets/qstring/main.cpp 68
5756 For historic reasons, this function does not handle
5757 thousands group separators. If you need to convert such numbers,
5758 use QLocale::toDouble().
5760 \snippet doc/src/snippets/qstring/main.cpp 69
5762 \sa number() QLocale::setDefault() QLocale::toDouble() trimmed()
5765 double QString::toDouble(bool *ok) const
5767 QLocale c_locale(QLocale::C);
5768 return c_locale.d()->stringToDouble(*this, ok, QLocalePrivate::FailOnGroupSeparators);
5772 Returns the string converted to a \c float value.
5774 If a conversion error occurs, *\a{ok} is set to false; otherwise
5775 *\a{ok} is set to true. Returns 0.0 if the conversion fails.
5777 The string conversion will always happen in the 'C' locale. For locale
5778 dependent conversion use QLocale::toFloat()
5782 \snippet doc/src/snippets/qstring/main.cpp 71
5784 \sa number(), toDouble(), toInt(), QLocale::toFloat()
5787 #define QT_MAX_FLOAT 3.4028234663852886e+38
5789 float QString::toFloat(bool *ok) const
5792 double d = toDouble(&myOk);
5793 if (!myOk || d > QT_MAX_FLOAT || d < -QT_MAX_FLOAT) {
5803 /*! \fn QString &QString::setNum(int n, int base)
5805 Sets the string to the printed value of \a n in the specified \a
5806 base, and returns a reference to the string.
5808 The base is 10 by default and must be between 2 and 36. For bases
5809 other than 10, \a n is treated as an unsigned integer.
5811 \snippet doc/src/snippets/qstring/main.cpp 56
5813 The formatting always uses QLocale::C, i.e., English/UnitedStates.
5814 To get a localized string representation of a number, use
5815 QLocale::toString() with the appropriate locale.
5818 /*! \fn QString &QString::setNum(uint n, int base)
5823 /*! \fn QString &QString::setNum(long n, int base)
5828 /*! \fn QString &QString::setNum(ulong n, int base)
5836 QString &QString::setNum(qlonglong n, int base)
5838 #if defined(QT_CHECK_RANGE)
5839 if (base < 2 || base > 36) {
5840 qWarning("QString::setNum: Invalid base (%d)", base);
5844 QLocale locale(QLocale::C);
5845 *this = locale.d()->longLongToString(n, -1, base);
5852 QString &QString::setNum(qulonglong n, int base)
5854 #if defined(QT_CHECK_RANGE)
5855 if (base < 2 || base > 36) {
5856 qWarning("QString::setNum: Invalid base (%d)", base);
5860 QLocale locale(QLocale::C);
5861 *this = locale.d()->unsLongLongToString(n, -1, base);
5865 /*! \fn QString &QString::setNum(short n, int base)
5870 /*! \fn QString &QString::setNum(ushort n, int base)
5876 \fn QString &QString::setNum(double n, char format, int precision)
5879 Sets the string to the printed value of \a n, formatted according
5880 to the given \a format and \a precision, and returns a reference
5883 The \a format can be 'f', 'F', 'e', 'E', 'g' or 'G' (see the
5884 arg() function documentation for an explanation of the formats).
5886 The formatting always uses QLocale::C, i.e., English/UnitedStates.
5887 To get a localized string representation of a number, use
5888 QLocale::toString() with the appropriate locale.
5891 QString &QString::setNum(double n, char f, int prec)
5893 QLocalePrivate::DoubleForm form = QLocalePrivate::DFDecimal;
5897 flags = QLocalePrivate::CapitalEorX;
5902 form = QLocalePrivate::DFDecimal;
5905 form = QLocalePrivate::DFExponent;
5908 form = QLocalePrivate::DFSignificantDigits;
5911 #if defined(QT_CHECK_RANGE)
5912 qWarning("QString::setNum: Invalid format char '%c'", f);
5917 QLocale locale(QLocale::C);
5918 *this = locale.d()->doubleToString(n, prec, form, -1, flags);
5923 \fn QString &QString::setNum(float n, char format, int precision)
5926 Sets the string to the printed value of \a n, formatted according
5927 to the given \a format and \a precision, and returns a reference
5930 The formatting always uses QLocale::C, i.e., English/UnitedStates.
5931 To get a localized string representation of a number, use
5932 QLocale::toString() with the appropriate locale.
5937 \fn QString QString::number(long n, int base)
5939 Returns a string equivalent of the number \a n according to the
5942 The base is 10 by default and must be between 2
5943 and 36. For bases other than 10, \a n is treated as an
5946 The formatting always uses QLocale::C, i.e., English/UnitedStates.
5947 To get a localized string representation of a number, use
5948 QLocale::toString() with the appropriate locale.
5950 \snippet doc/src/snippets/qstring/main.cpp 35
5955 QString QString::number(long n, int base)
5963 \fn QString QString::number(ulong n, int base)
5967 QString QString::number(ulong n, int base)
5977 QString QString::number(int n, int base)
5987 QString QString::number(uint n, int base)
5997 QString QString::number(qlonglong n, int base)
6007 QString QString::number(qulonglong n, int base)
6016 \fn QString QString::number(double n, char format, int precision)
6018 Returns a string equivalent of the number \a n, formatted
6019 according to the specified \a format and \a precision. See
6020 \l{Argument Formats} for details.
6022 Unlike QLocale::toString(), this function does not honor the
6023 user's locale settings.
6025 \sa setNum(), QLocale::toString()
6027 QString QString::number(double n, char f, int prec)
6030 s.setNum(n, f, prec);
6035 Splits the string into substrings wherever \a sep occurs, and
6036 returns the list of those strings. If \a sep does not match
6037 anywhere in the string, split() returns a single-element list
6038 containing this string.
6040 \a cs specifies whether \a sep should be matched case
6041 sensitively or case insensitively.
6043 If \a behavior is QString::SkipEmptyParts, empty entries don't
6044 appear in the result. By default, empty entries are kept.
6048 \snippet doc/src/snippets/qstring/main.cpp 62
6050 \sa QStringList::join(), section()
6052 QStringList QString::split(const QString &sep, SplitBehavior behavior, Qt::CaseSensitivity cs) const
6058 while ((end = indexOf(sep, start + extra, cs)) != -1) {
6059 if (start != end || behavior == KeepEmptyParts)
6060 list.append(mid(start, end - start));
6061 start = end + sep.size();
6062 extra = (sep.size() == 0 ? 1 : 0);
6064 if (start != size() || behavior == KeepEmptyParts)
6065 list.append(mid(start));
6072 QStringList QString::split(QChar sep, SplitBehavior behavior, Qt::CaseSensitivity cs) const
6077 while ((end = indexOf(sep, start, cs)) != -1) {
6078 if (start != end || behavior == KeepEmptyParts)
6079 list.append(mid(start, end - start));
6082 if (start != size() || behavior == KeepEmptyParts)
6083 list.append(mid(start));
6087 #ifndef QT_NO_REGEXP
6091 Splits the string into substrings wherever the regular expression
6092 \a rx matches, and returns the list of those strings. If \a rx
6093 does not match anywhere in the string, split() returns a
6094 single-element list containing this string.
6096 Here's an example where we extract the words in a sentence
6097 using one or more whitespace characters as the separator:
6099 \snippet doc/src/snippets/qstring/main.cpp 59
6101 Here's a similar example, but this time we use any sequence of
6102 non-word characters as the separator:
6104 \snippet doc/src/snippets/qstring/main.cpp 60
6106 Here's a third example where we use a zero-length assertion,
6107 \bold{\\b} (word boundary), to split the string into an
6108 alternating sequence of non-word and word tokens:
6110 \snippet doc/src/snippets/qstring/main.cpp 61
6112 \sa QStringList::join(), section()
6114 QStringList QString::split(const QRegExp &rx, SplitBehavior behavior) const
6121 while ((end = rx2.indexIn(*this, start + extra)) != -1) {
6122 int matchedLen = rx2.matchedLength();
6123 if (start != end || behavior == KeepEmptyParts)
6124 list.append(mid(start, end - start));
6125 start = end + matchedLen;
6126 extra = (matchedLen == 0) ? 1 : 0;
6128 if (start != size() || behavior == KeepEmptyParts)
6129 list.append(mid(start));
6135 \enum QString::NormalizationForm
6137 This enum describes the various normalized forms of Unicode text.
6139 \value NormalizationForm_D Canonical Decomposition
6140 \value NormalizationForm_C Canonical Decomposition followed by Canonical Composition
6141 \value NormalizationForm_KD Compatibility Decomposition
6142 \value NormalizationForm_KC Compatibility Decomposition followed by Canonical Composition
6145 {http://www.unicode.org/reports/tr15/}{Unicode Standard Annex #15}
6149 \fn QString QString::normalized(NormalizationForm mode) const
6150 Returns the string in the given Unicode normalization \a mode.
6152 QString QString::normalized(QString::NormalizationForm mode) const
6154 return normalized(mode, UNICODE_DATA_VERSION);
6160 Returns a copy of this string repeated the specified number of \a times.
6162 If \a times is less than 1, an empty string is returned.
6168 str.repeated(4); // returns "abababab"
6171 QString QString::repeated(int times) const
6182 const int resultSize = times * d->size;
6185 result.reserve(resultSize);
6186 if (int(result.d->alloc) != resultSize)
6187 return QString(); // not enough memory
6189 memcpy(result.d->data(), d->data(), d->size * sizeof(ushort));
6191 int sizeSoFar = d->size;
6192 ushort *end = result.d->data() + sizeSoFar;
6194 const int halfResultSize = resultSize >> 1;
6195 while (sizeSoFar <= halfResultSize) {
6196 memcpy(end, result.d->data(), sizeSoFar * sizeof(ushort));
6200 memcpy(end, result.d->data(), (resultSize - sizeSoFar) * sizeof(ushort));
6201 result.d->data()[resultSize] = '\0';
6202 result.d->size = resultSize;
6206 void qt_string_normalize(QString *data, QString::NormalizationForm mode, QChar::UnicodeVersion version, int from);
6209 \fn QString QString::normalized(NormalizationForm mode, QChar::UnicodeVersion version) const
6211 Returns the string in the given Unicode normalization \a mode,
6212 according to the given \a version of the Unicode standard.
6214 QString QString::normalized(QString::NormalizationForm mode, QChar::UnicodeVersion version) const
6216 QString copy = *this;
6217 qt_string_normalize(©, mode, version, 0);
6221 void qt_string_normalize(QString *data, QString::NormalizationForm mode, QChar::UnicodeVersion version, int from)
6224 const QChar *p = data->constData();
6225 int len = data->length();
6226 for (int i = from; i < len; ++i) {
6227 if (p[i].unicode() >= 0x80) {
6235 if (version == QChar::Unicode_Unassigned) {
6236 version = UNICODE_DATA_VERSION;
6237 } else if (version != UNICODE_DATA_VERSION) {
6238 const QString &s = *data;
6240 for (int i = 0; i < NumNormalizationCorrections; ++i) {
6241 const NormalizationCorrection &n = uc_normalization_corrections[i];
6242 if (n.version > version) {
6244 if (QChar::requiresSurrogates(n.ucs4)) {
6245 ushort ucs4High = QChar::highSurrogate(n.ucs4);
6246 ushort ucs4Low = QChar::lowSurrogate(n.ucs4);
6247 ushort oldHigh = QChar::highSurrogate(n.old_mapping);
6248 ushort oldLow = QChar::lowSurrogate(n.old_mapping);
6249 while (pos < s.length() - 1) {
6250 if (s.at(pos).unicode() == ucs4High && s.at(pos + 1).unicode() == ucs4Low) {
6253 d[pos] = QChar(oldHigh);
6254 d[++pos] = QChar(oldLow);
6259 while (pos < s.length()) {
6260 if (s.at(pos).unicode() == n.ucs4) {
6263 d[pos] = QChar(n.old_mapping);
6271 decomposeHelper(data, mode < QString::NormalizationForm_KD, version, from);
6273 canonicalOrderHelper(data, version, from);
6275 if (mode == QString::NormalizationForm_D || mode == QString::NormalizationForm_KD)
6278 composeHelper(data, version, from);
6282 struct ArgEscapeData
6284 int min_escape; // lowest escape sequence number
6285 int occurrences; // number of occurrences of the lowest escape sequence number
6286 int locale_occurrences; // number of occurrences of the lowest escape sequence number that
6288 int escape_len; // total length of escape sequences which will be replaced
6291 static ArgEscapeData findArgEscapes(const QString &s)
6293 const QChar *uc_begin = s.unicode();
6294 const QChar *uc_end = uc_begin + s.length();
6298 d.min_escape = INT_MAX;
6301 d.locale_occurrences = 0;
6303 const QChar *c = uc_begin;
6304 while (c != uc_end) {
6305 while (c != uc_end && c->unicode() != '%')
6310 const QChar *escape_start = c;
6314 bool locale_arg = false;
6315 if (c->unicode() == 'L') {
6321 if (c->digitValue() == -1)
6324 int escape = c->digitValue();
6327 if (c != uc_end && c->digitValue() != -1) {
6328 escape = (10 * escape) + c->digitValue();
6332 if (escape > d.min_escape)
6335 if (escape < d.min_escape) {
6336 d.min_escape = escape;
6339 d.locale_occurrences = 0;
6344 ++d.locale_occurrences;
6345 d.escape_len += c - escape_start;
6350 static QString replaceArgEscapes(const QString &s, const ArgEscapeData &d, int field_width,
6351 const QString &arg, const QString &larg, QChar fillChar = QLatin1Char(' '))
6353 const QChar *uc_begin = s.unicode();
6354 const QChar *uc_end = uc_begin + s.length();
6356 int abs_field_width = qAbs(field_width);
6357 int result_len = s.length()
6359 + (d.occurrences - d.locale_occurrences)
6360 *qMax(abs_field_width, arg.length())
6361 + d.locale_occurrences
6362 *qMax(abs_field_width, larg.length());
6364 QString result(result_len, Qt::Uninitialized);
6365 QChar *result_buff = (QChar*) result.unicode();
6367 QChar *rc = result_buff;
6368 const QChar *c = uc_begin;
6370 while (c != uc_end) {
6371 /* We don't have to check if we run off the end of the string with c,
6372 because as long as d.occurrences > 0 we KNOW there are valid escape
6375 const QChar *text_start = c;
6377 while (c->unicode() != '%')
6380 const QChar *escape_start = c++;
6382 bool locale_arg = false;
6383 if (c->unicode() == 'L') {
6388 int escape = c->digitValue();
6390 if (c + 1 != uc_end && (c + 1)->digitValue() != -1) {
6391 escape = (10 * escape) + (c + 1)->digitValue();
6396 if (escape != d.min_escape) {
6397 memcpy(rc, text_start, (c - text_start)*sizeof(QChar));
6398 rc += c - text_start;
6403 memcpy(rc, text_start, (escape_start - text_start)*sizeof(QChar));
6404 rc += escape_start - text_start;
6408 pad_chars = qMax(abs_field_width, larg.length()) - larg.length();
6410 pad_chars = qMax(abs_field_width, arg.length()) - arg.length();
6412 if (field_width > 0) { // left padded
6413 for (uint i = 0; i < pad_chars; ++i)
6414 (rc++)->unicode() = fillChar.unicode();
6418 memcpy(rc, larg.unicode(), larg.length()*sizeof(QChar));
6419 rc += larg.length();
6422 memcpy(rc, arg.unicode(), arg.length()*sizeof(QChar));
6426 if (field_width < 0) { // right padded
6427 for (uint i = 0; i < pad_chars; ++i)
6428 (rc++)->unicode() = fillChar.unicode();
6431 if (++repl_cnt == d.occurrences) {
6432 memcpy(rc, c, (uc_end - c)*sizeof(QChar));
6434 Q_ASSERT(rc - result_buff == result_len);
6439 Q_ASSERT(rc == result_buff + result_len);
6445 Returns a copy of this string with the lowest numbered place marker
6446 replaced by string \a a, i.e., \c %1, \c %2, ..., \c %99.
6448 \a fieldWidth specifies the minimum amount of space that argument \a
6449 a shall occupy. If \a a requires less space than \a fieldWidth, it
6450 is padded to \a fieldWidth with character \a fillChar. A positive
6451 \a fieldWidth produces right-aligned text. A negative \a fieldWidth
6452 produces left-aligned text.
6454 This example shows how we might create a \c status string for
6455 reporting progress while processing a list of files:
6457 \snippet doc/src/snippets/qstring/main.cpp 11
6459 First, \c arg(i) replaces \c %1. Then \c arg(total) replaces \c
6460 %2. Finally, \c arg(fileName) replaces \c %3.
6462 One advantage of using arg() over sprintf() is that the order of the
6463 numbered place markers can change, if the application's strings are
6464 translated into other languages, but each arg() will still replace
6465 the lowest numbered unreplaced place marker, no matter where it
6466 appears. Also, if place marker \c %i appears more than once in the
6467 string, the arg() replaces all of them.
6469 If there is no unreplaced place marker remaining, a warning message
6470 is output and the result is undefined. Place marker numbers must be
6471 in the range 1 to 99.
6473 QString QString::arg(const QString &a, int fieldWidth, QChar fillChar) const
6475 ArgEscapeData d = findArgEscapes(*this);
6477 if (d.occurrences == 0) {
6478 qWarning("QString::arg: Argument missing: %s, %s", toLocal8Bit().data(),
6479 a.toLocal8Bit().data());
6482 return replaceArgEscapes(*this, d, fieldWidth, a, a, fillChar);
6486 \fn QString QString::arg(const QString& a1, const QString& a2) const
6489 This is the same as \c {str.arg(a1).arg(a2)}, except that the
6490 strings \a a1 and \a a2 are replaced in one pass. This can make a
6491 difference if \a a1 contains e.g. \c{%1}:
6493 \snippet doc/src/snippets/qstring/main.cpp 13
6497 \fn QString QString::arg(const QString& a1, const QString& a2, const QString& a3) const
6500 This is the same as calling \c str.arg(a1).arg(a2).arg(a3), except
6501 that the strings \a a1, \a a2 and \a a3 are replaced in one pass.
6505 \fn QString QString::arg(const QString& a1, const QString& a2, const QString& a3, const QString& a4) const
6508 This is the same as calling \c
6509 {str.arg(a1).arg(a2).arg(a3).arg(a4)}, except that the strings \a
6510 a1, \a a2, \a a3 and \a a4 are replaced in one pass.
6514 \fn QString QString::arg(const QString& a1, const QString& a2, const QString& a3, const QString& a4, const QString& a5) const
6517 This is the same as calling \c
6518 {str.arg(a1).arg(a2).arg(a3).arg(a4).arg(a5)}, except that the strings
6519 \a a1, \a a2, \a a3, \a a4, and \a a5 are replaced in one pass.
6523 \fn QString QString::arg(const QString& a1, const QString& a2, const QString& a3, const QString& a4, const QString& a5, const QString& a6) const
6526 This is the same as calling \c
6527 {str.arg(a1).arg(a2).arg(a3).arg(a4).arg(a5).arg(a6))}, except that
6528 the strings \a a1, \a a2, \a a3, \a a4, \a a5, and \a a6 are
6529 replaced in one pass.
6533 \fn QString QString::arg(const QString& a1, const QString& a2, const QString& a3, const QString& a4, const QString& a5, const QString& a6, const QString& a7) const
6536 This is the same as calling \c
6537 {str.arg(a1).arg(a2).arg(a3).arg(a4).arg(a5).arg(a6).arg(a7)},
6538 except that the strings \a a1, \a a2, \a a3, \a a4, \a a5, \a a6,
6539 and \a a7 are replaced in one pass.
6543 \fn QString QString::arg(const QString& a1, const QString& a2, const QString& a3, const QString& a4, const QString& a5, const QString& a6, const QString& a7, const QString& a8) const
6546 This is the same as calling \c
6547 {str.arg(a1).arg(a2).arg(a3).arg(a4).arg(a5).arg(a6).arg(a7).arg(a8)},
6548 except that the strings \a a1, \a a2, \a a3, \a a4, \a a5, \a a6, \a
6549 a7, and \a a8 are replaced in one pass.
6553 \fn QString QString::arg(const QString& a1, const QString& a2, const QString& a3, const QString& a4, const QString& a5, const QString& a6, const QString& a7, const QString& a8, const QString& a9) const
6556 This is the same as calling \c
6557 {str.arg(a1).arg(a2).arg(a3).arg(a4).arg(a5).arg(a6).arg(a7).arg(a8).arg(a9)},
6558 except that the strings \a a1, \a a2, \a a3, \a a4, \a a5, \a a6, \a
6559 a7, \a a8, and \a a9 are replaced in one pass.
6562 /*! \fn QString QString::arg(int a, int fieldWidth, int base, QChar fillChar) const
6565 The \a a argument is expressed in base \a base, which is 10 by
6566 default and must be between 2 and 36. For bases other than 10, \a a
6567 is treated as an unsigned integer.
6569 \a fieldWidth specifies the minimum amount of space that \a a is
6570 padded to and filled with the character \a fillChar. A positive
6571 value produces right-aligned text; a negative value produces
6574 The '%' can be followed by an 'L', in which case the sequence is
6575 replaced with a localized representation of \a a. The conversion
6576 uses the default locale, set by QLocale::setDefault(). If no default
6577 locale was specified, the "C" locale is used. The 'L' flag is
6578 ignored if \a base is not 10.
6580 \snippet doc/src/snippets/qstring/main.cpp 12
6581 \snippet doc/src/snippets/qstring/main.cpp 14
6583 If \a fillChar is '0' (the number 0, ASCII 48), the locale's zero is
6584 used. For negative numbers, zero padding might appear before the
6588 /*! \fn QString QString::arg(uint a, int fieldWidth, int base, QChar fillChar) const
6591 The \a base argument specifies the base to use when converting the
6592 integer \a a into a string. The base must be between 2 and 36.
6594 If \a fillChar is '0' (the number 0, ASCII 48), the locale's zero is
6595 used. For negative numbers, zero padding might appear before the
6599 /*! \fn QString QString::arg(long a, int fieldWidth, int base, QChar fillChar) const
6602 \a fieldWidth specifies the minimum amount of space that \a a is
6603 padded to and filled with the character \a fillChar. A positive
6604 value produces right-aligned text; a negative value produces
6607 The \a a argument is expressed in the given \a base, which is 10 by
6608 default and must be between 2 and 36.
6610 The '%' can be followed by an 'L', in which case the sequence is
6611 replaced with a localized representation of \a a. The conversion
6612 uses the default locale. The default locale is determined from the
6613 system's locale settings at application startup. It can be changed
6614 using QLocale::setDefault(). The 'L' flag is ignored if \a base is
6617 \snippet doc/src/snippets/qstring/main.cpp 12
6618 \snippet doc/src/snippets/qstring/main.cpp 14
6620 If \a fillChar is '0' (the number 0, ASCII 48), the locale's zero is
6621 used. For negative numbers, zero padding might appear before the
6625 /*! \fn QString QString::arg(ulong a, int fieldWidth, int base, QChar fillChar) const
6628 \a fieldWidth specifies the minimum amount of space that \a a is
6629 padded to and filled with the character \a fillChar. A positive
6630 value produces right-aligned text; a negative value produces
6633 The \a base argument specifies the base to use when converting the
6634 integer \a a to a string. The base must be between 2 and 36, with 8
6635 giving octal, 10 decimal, and 16 hexadecimal numbers.
6637 If \a fillChar is '0' (the number 0, ASCII 48), the locale's zero is
6638 used. For negative numbers, zero padding might appear before the
6645 \a fieldWidth specifies the minimum amount of space that \a a is
6646 padded to and filled with the character \a fillChar. A positive
6647 value produces right-aligned text; a negative value produces
6650 The \a base argument specifies the base to use when converting the
6651 integer \a a into a string. The base must be between 2 and 36, with
6652 8 giving octal, 10 decimal, and 16 hexadecimal numbers.
6654 If \a fillChar is '0' (the number 0, ASCII 48), the locale's zero is
6655 used. For negative numbers, zero padding might appear before the
6658 QString QString::arg(qlonglong a, int fieldWidth, int base, QChar fillChar) const
6660 ArgEscapeData d = findArgEscapes(*this);
6662 if (d.occurrences == 0) {
6663 qWarning() << "QString::arg: Argument missing:" << *this << ',' << a;
6667 unsigned flags = QLocalePrivate::NoFlags;
6668 if (fillChar == QLatin1Char('0'))
6669 flags = QLocalePrivate::ZeroPadded;
6672 if (d.occurrences > d.locale_occurrences)
6673 arg = QLocale::c().d()->longLongToString(a, -1, base, fieldWidth, flags);
6676 if (d.locale_occurrences > 0) {
6678 if (!locale.numberOptions() & QLocale::OmitGroupSeparator)
6679 flags |= QLocalePrivate::ThousandsGroup;
6680 locale_arg = locale.d()->longLongToString(a, -1, base, fieldWidth, flags);
6683 return replaceArgEscapes(*this, d, fieldWidth, arg, locale_arg, fillChar);
6689 \a fieldWidth specifies the minimum amount of space that \a a is
6690 padded to and filled with the character \a fillChar. A positive
6691 value produces right-aligned text; a negative value produces
6694 The \a base argument specifies the base to use when converting the
6695 integer \a a into a string. \a base must be between 2 and 36, with 8
6696 giving octal, 10 decimal, and 16 hexadecimal numbers.
6698 If \a fillChar is '0' (the number 0, ASCII 48), the locale's zero is
6699 used. For negative numbers, zero padding might appear before the
6702 QString QString::arg(qulonglong a, int fieldWidth, int base, QChar fillChar) const
6704 ArgEscapeData d = findArgEscapes(*this);
6706 if (d.occurrences == 0) {
6707 qWarning() << "QString::arg: Argument missing:" << *this << ',' << a;
6711 unsigned flags = QLocalePrivate::NoFlags;
6712 if (fillChar == QLatin1Char('0'))
6713 flags = QLocalePrivate::ZeroPadded;
6716 if (d.occurrences > d.locale_occurrences)
6717 arg = QLocale::c().d()->unsLongLongToString(a, -1, base, fieldWidth, flags);
6720 if (d.locale_occurrences > 0) {
6722 if (!locale.numberOptions() & QLocale::OmitGroupSeparator)
6723 flags |= QLocalePrivate::ThousandsGroup;
6724 locale_arg = locale.d()->unsLongLongToString(a, -1, base, fieldWidth, flags);
6727 return replaceArgEscapes(*this, d, fieldWidth, arg, locale_arg, fillChar);
6733 \fn QString QString::arg(short a, int fieldWidth, int base, QChar fillChar) const
6735 \a fieldWidth specifies the minimum amount of space that \a a is
6736 padded to and filled with the character \a fillChar. A positive
6737 value produces right-aligned text; a negative value produces
6740 The \a base argument specifies the base to use when converting the
6741 integer \a a into a string. The base must be between 2 and 36, with
6742 8 giving octal, 10 decimal, and 16 hexadecimal numbers.
6744 If \a fillChar is '0' (the number 0, ASCII 48), the locale's zero is
6745 used. For negative numbers, zero padding might appear before the
6750 \fn QString QString::arg(ushort a, int fieldWidth, int base, QChar fillChar) const
6753 \a fieldWidth specifies the minimum amount of space that \a a is
6754 padded to and filled with the character \a fillChar. A positive
6755 value produces right-aligned text; a negative value produces
6758 The \a base argument specifies the base to use when converting the
6759 integer \a a into a string. The base must be between 2 and 36, with
6760 8 giving octal, 10 decimal, and 16 hexadecimal numbers.
6762 If \a fillChar is '0' (the number 0, ASCII 48), the locale's zero is
6763 used. For negative numbers, zero padding might appear before the
6770 QString QString::arg(QChar a, int fieldWidth, QChar fillChar) const
6774 return arg(c, fieldWidth, fillChar);
6780 The \a a argument is interpreted as a Latin-1 character.
6782 QString QString::arg(char a, int fieldWidth, QChar fillChar) const
6785 c += QLatin1Char(a);
6786 return arg(c, fieldWidth, fillChar);
6790 \fn QString QString::arg(double a, int fieldWidth, char format, int precision, QChar fillChar) const
6793 Argument \a a is formatted according to the specified \a format and
6794 \a precision. See \l{Argument Formats} for details.
6796 \a fieldWidth specifies the minimum amount of space that \a a is
6797 padded to and filled with the character \a fillChar. A positive
6798 value produces right-aligned text; a negative value produces
6801 \snippet doc/src/snippets/code/src_corelib_tools_qstring.cpp 2
6803 The '%' can be followed by an 'L', in which case the sequence is
6804 replaced with a localized representation of \a a. The conversion
6805 uses the default locale, set by QLocale::setDefaultLocale(). If no
6806 default locale was specified, the "C" locale is used.
6808 If \a fillChar is '0' (the number 0, ASCII 48), this function will
6809 use the locale's zero to pad. For negative numbers, the zero padding
6810 will probably appear before the minus sign.
6812 \sa QLocale::toString()
6814 QString QString::arg(double a, int fieldWidth, char fmt, int prec, QChar fillChar) const
6816 ArgEscapeData d = findArgEscapes(*this);
6818 if (d.occurrences == 0) {
6819 qWarning("QString::arg: Argument missing: %s, %g", toLocal8Bit().data(), a);
6823 unsigned flags = QLocalePrivate::NoFlags;
6824 if (fillChar == QLatin1Char('0'))
6825 flags = QLocalePrivate::ZeroPadded;
6828 flags |= QLocalePrivate::CapitalEorX;
6829 fmt = qToLower(fmt);
6831 QLocalePrivate::DoubleForm form = QLocalePrivate::DFDecimal;
6834 form = QLocalePrivate::DFDecimal;
6837 form = QLocalePrivate::DFExponent;
6840 form = QLocalePrivate::DFSignificantDigits;
6843 #if defined(QT_CHECK_RANGE)
6844 qWarning("QString::arg: Invalid format char '%c'", fmt);
6850 if (d.occurrences > d.locale_occurrences)
6851 arg = QLocale::c().d()->doubleToString(a, prec, form, fieldWidth, flags);
6854 if (d.locale_occurrences > 0) {
6857 if (!locale.numberOptions() & QLocale::OmitGroupSeparator)
6858 flags |= QLocalePrivate::ThousandsGroup;
6859 locale_arg = locale.d()->doubleToString(a, prec, form, fieldWidth, flags);
6862 return replaceArgEscapes(*this, d, fieldWidth, arg, locale_arg, fillChar);
6865 static int getEscape(const QChar *uc, int *pos, int len, int maxNumber = 999)
6869 if (i < len && uc[i] == QLatin1Char('L'))
6872 int escape = uc[i].unicode() - '0';
6873 if (uint(escape) >= 10U)
6877 int digit = uc[i].unicode() - '0';
6878 if (uint(digit) >= 10U)
6880 escape = (escape * 10) + digit;
6883 if (escape <= maxNumber) {
6891 QString QString::multiArg(int numArgs, const QString **args) const
6894 QMap<int, int> numbersUsed;
6895 const QChar *uc = (const QChar *) d->data();
6896 const int len = d->size;
6897 const int end = len - 1;
6898 int lastNumber = -1;
6901 // populate the numbersUsed map with the %n's that actually occur in the string
6903 if (uc[i] == QLatin1Char('%')) {
6904 int number = getEscape(uc, &i, len);
6906 numbersUsed.insert(number, -1);
6913 // assign an argument number to each of the %n's
6914 QMap<int, int>::iterator j = numbersUsed.begin();
6915 QMap<int, int>::iterator jend = numbersUsed.end();
6917 while (j != jend && arg < numArgs) {
6919 lastNumber = j.key();
6924 if (numArgs > arg) {
6925 qWarning("QString::arg: %d argument(s) missing in %s", numArgs - arg, toLocal8Bit().data());
6931 if (uc[i] == QLatin1Char('%') && i != end) {
6932 int number = getEscape(uc, &i, len, lastNumber);
6933 int arg = numbersUsed[number];
6934 if (number != -1 && arg != -1) {
6935 result += *args[arg];
6945 /*! \fn bool QString::isSimpleText() const
6949 bool QString::isSimpleText() const
6951 const ushort *p = d->data();
6952 const ushort * const end = p + d->size;
6955 // sort out regions of complex text formatting
6956 if (uc > 0x058f && (uc < 0x1100 || uc > 0xfb0f)) {
6965 /*! \fn bool QString::isRightToLeft() const
6967 Returns true if the string is read right to left.
6969 bool QString::isRightToLeft() const
6971 const ushort *p = d->data();
6972 const ushort * const end = p + d->size;
6974 switch(QChar::direction(*p))
6989 /*! \fn QChar *QString::data()
6991 Returns a pointer to the data stored in the QString. The pointer
6992 can be used to access and modify the characters that compose the
6993 string. For convenience, the data is '\\0'-terminated.
6997 \snippet doc/src/snippets/qstring/main.cpp 19
6999 Note that the pointer remains valid only as long as the string is
7000 not modified by other means. For read-only access, constData() is
7001 faster because it never causes a \l{deep copy} to occur.
7003 \sa constData(), operator[]()
7006 /*! \fn const QChar *QString::data() const
7011 /*! \fn const QChar *QString::constData() const
7013 Returns a pointer to the data stored in the QString. The pointer
7014 can be used to access the characters that compose the string. For
7015 convenience, the data is '\\0'-terminated.
7017 Note that the pointer remains valid only as long as the string is
7020 \sa data(), operator[]()
7023 /*! \fn void QString::push_front(const QString &other)
7025 This function is provided for STL compatibility, prepending the
7026 given \a other string to the beginning of this string. It is
7027 equivalent to \c prepend(other).
7032 /*! \fn void QString::push_front(QChar ch)
7036 Prepends the given \a ch character to the beginning of this string.
7039 /*! \fn void QString::push_back(const QString &other)
7041 This function is provided for STL compatibility, appending the
7042 given \a other string onto the end of this string. It is
7043 equivalent to \c append(other).
7048 /*! \fn void QString::push_back(QChar ch)
7052 Appends the given \a ch character onto the end of this string.
7056 \fn std::string QString::toStdString() const
7058 Returns a std::string object with the data contained in this
7059 QString. The Unicode data is converted into 8-bit characters using
7060 the toAscii() function.
7062 This operator is mostly useful to pass a QString to a function
7063 that accepts a std::string object.
7065 If the QString contains Unicode characters that the
7066 QTextCodec::codecForCStrings() codec cannot handle, using this operator
7067 can lead to loss of information.
7069 This operator is only available if Qt is configured with STL
7070 compatibility enabled and if QT_NO_STL is not defined.
7072 \sa toAscii(), toLatin1(), toUtf8(), toLocal8Bit()
7076 Constructs a QString that uses the first \a size Unicode characters
7077 in the array \a unicode. The data in \a unicode is \e not
7078 copied. The caller must be able to guarantee that \a unicode will
7079 not be deleted or modified as long as the QString (or an
7080 unmodified copy of it) exists.
7082 Any attempts to modify the QString or copies of it will cause it
7083 to create a deep copy of the data, ensuring that the raw data
7086 Here's an example of how we can use a QRegExp on raw data in
7087 memory without requiring to copy the data into a QString:
7089 \snippet doc/src/snippets/qstring/main.cpp 22
7090 \snippet doc/src/snippets/qstring/main.cpp 23
7092 \warning A string created with fromRawData() is \e not
7093 '\\0'-terminated, unless the raw data contains a '\\0' character
7094 at position \a size. This means unicode() will \e not return a
7095 '\\0'-terminated string (although utf16() does, at the cost of
7096 copying the raw data).
7098 \sa fromUtf16(), setRawData()
7100 QString QString::fromRawData(const QChar *unicode, int size)
7104 x = const_cast<Data *>(&shared_null.str);
7106 x = const_cast<Data *>(&shared_empty.str);
7108 x = static_cast<Data *>(::malloc(sizeof(Data) + sizeof(ushort)));
7113 x->capacityReserved = false;
7114 x->offset = (const ushort *)unicode - (x->d + sizeof(qptrdiff)/sizeof(ushort));
7116 return QString(x, 0);
7122 Resets the QString to use the first \a size Unicode characters
7123 in the array \a unicode. The data in \a unicode is \e not
7124 copied. The caller must be able to guarantee that \a unicode will
7125 not be deleted or modified as long as the QString (or an
7126 unmodified copy of it) exists.
7128 This function can be used instead of fromRawData() to re-use
7129 existings QString objects to save memory re-allocations.
7133 QString &QString::setRawData(const QChar *unicode, int size)
7135 if (d->ref != 1 || d->alloc) {
7136 *this = fromRawData(unicode, size);
7140 d->offset = (const ushort *)unicode - (d->d + sizeof(qptrdiff)/sizeof(ushort));
7149 /*! \class QLatin1String
7150 \brief The QLatin1String class provides a thin wrapper around an US-ASCII/Latin-1 encoded string literal.
7152 \ingroup string-processing
7155 Many of QString's member functions are overloaded to accept
7156 \c{const char *} instead of QString. This includes the copy
7157 constructor, the assignment operator, the comparison operators,
7158 and various other functions such as \link QString::insert()
7159 insert() \endlink, \link QString::replace() replace()\endlink,
7160 and \link QString::indexOf() indexOf()\endlink. These functions
7161 are usually optimized to avoid constructing a QString object for
7162 the \c{const char *} data. For example, assuming \c str is a
7165 \snippet doc/src/snippets/code/src_corelib_tools_qstring.cpp 3
7169 \snippet doc/src/snippets/code/src_corelib_tools_qstring.cpp 4
7171 because it doesn't construct four temporary QString objects and
7172 make a deep copy of the character data.
7174 Applications that define \c QT_NO_CAST_FROM_ASCII (as explained
7175 in the QString documentation) don't have access to QString's
7176 \c{const char *} API. To provide an efficient way of specifying
7177 constant Latin-1 strings, Qt provides the QLatin1String, which is
7178 just a very thin wrapper around a \c{const char *}. Using
7179 QLatin1String, the example code above becomes
7181 \snippet doc/src/snippets/code/src_corelib_tools_qstring.cpp 5
7183 This is a bit longer to type, but it provides exactly the same
7184 benefits as the first version of the code, and is faster than
7185 converting the Latin-1 strings using QString::fromLatin1().
7187 Thanks to the QString(const QLatin1String &) constructor,
7188 QLatin1String can be used everywhere a QString is expected. For
7191 \snippet doc/src/snippets/code/src_corelib_tools_qstring.cpp 6
7193 \sa QString, QLatin1Char, QStringLiteral
7196 /*! \fn QLatin1String::QLatin1String(const char *str)
7198 Constructs a QLatin1String object that stores \a str. Note that if
7199 \a str is 0, an empty string is created; this case is handled by
7202 The string data is \e not copied. The caller must be able to
7203 guarantee that \a str will not be deleted or modified as long as
7204 the QLatin1String object exists.
7209 /*! \fn QLatin1String::QLatin1String(const char *str, int size)
7211 Constructs a QLatin1String object that stores \a str with \a size.
7212 Note that if \a str is 0, an empty string is created; this case
7213 is handled by QString.
7215 The string data is \e not copied. The caller must be able to
7216 guarantee that \a str will not be deleted or modified as long as
7217 the QLatin1String object exists.
7222 /*! \fn const char *QLatin1String::latin1() const
7224 Returns the Latin-1 string stored in this object.
7227 /*! \fn int QLatin1String::size() const
7229 Returns the size of the Latin-1 string stored in this object.
7232 /*! \fn bool QLatin1String::operator==(const QString &other) const
7234 Returns true if this string is equal to string \a other;
7235 otherwise returns false.
7237 The comparison is based exclusively on the numeric Unicode values
7238 of the characters and is very fast, but is not what a human would
7239 expect. Consider sorting user-interface strings with
7240 QString::localeAwareCompare().
7244 \fn bool QLatin1String::operator==(const char *other) const
7248 The \a other const char pointer is converted to a QString using
7249 the QString::fromAscii() function.
7251 You can disable this operator by defining \c
7252 QT_NO_CAST_FROM_ASCII when you compile your applications. This
7253 can be useful if you want to ensure that all user-visible strings
7254 go through QObject::tr(), for example.
7257 /*! \fn bool QLatin1String::operator!=(const QString &other) const
7259 Returns true if this string is not equal to string \a other;
7260 otherwise returns false.
7262 The comparison is based exclusively on the numeric Unicode values
7263 of the characters and is very fast, but is not what a human would
7264 expect. Consider sorting user-interface strings with
7265 QString::localeAwareCompare().
7269 \fn bool QLatin1String::operator!=(const char *other) const
7271 \overload operator!=()
7273 The \a other const char pointer is converted to a QString using
7274 the QString::fromAscii() function.
7276 You can disable this operator by defining \c
7277 QT_NO_CAST_FROM_ASCII when you compile your applications. This
7278 can be useful if you want to ensure that all user-visible strings
7279 go through QObject::tr(), for example.
7283 \fn bool QLatin1String::operator>(const QString &other) const
7285 Returns true if this string is lexically greater than string \a
7286 other; otherwise returns false.
7288 The comparison is based exclusively on the numeric Unicode values
7289 of the characters and is very fast, but is not what a human would
7290 expect. Consider sorting user-interface strings with
7291 QString::localeAwareCompare().
7295 \fn bool QLatin1String::operator>(const char *other) const
7299 The \a other const char pointer is converted to a QString using
7300 the QString::fromAscii() function.
7302 You can disable this operator by defining \c QT_NO_CAST_FROM_ASCII
7303 when you compile your applications. This can be useful if you want
7304 to ensure that all user-visible strings go through QObject::tr(),
7309 \fn bool QLatin1String::operator<(const QString &other) const
7311 Returns true if this string is lexically less than the \a other
7312 string; otherwise returns false.
7314 The comparison is based exclusively on the numeric Unicode values
7315 of the characters and is very fast, but is not what a human would
7316 expect. Consider sorting user-interface strings using the
7317 QString::localeAwareCompare() function.
7321 \fn bool QLatin1String::operator<(const char *other) const
7325 The \a other const char pointer is converted to a QString using
7326 the QString::fromAscii() function.
7328 You can disable this operator by defining \c
7329 QT_NO_CAST_FROM_ASCII when you compile your applications. This
7330 can be useful if you want to ensure that all user-visible strings
7331 go through QObject::tr(), for example.
7335 \fn bool QLatin1String::operator>=(const QString &other) const
7337 Returns true if this string is lexically greater than or equal
7338 to string \a other; otherwise returns false.
7340 The comparison is based exclusively on the numeric Unicode values
7341 of the characters and is very fast, but is not what a human would
7342 expect. Consider sorting user-interface strings with
7343 QString::localeAwareCompare().
7347 \fn bool QLatin1String::operator>=(const char *other) const
7351 The \a other const char pointer is converted to a QString using
7352 the QString::fromAscii() function.
7354 You can disable this operator by defining \c
7355 QT_NO_CAST_FROM_ASCII when you compile your applications. This
7356 can be useful if you want to ensure that all user-visible strings
7357 go through QObject::tr(), for example.
7360 /*! \fn bool QLatin1String::operator<=(const QString &other) const
7362 Returns true if this string is lexically less than or equal
7363 to string \a other; otherwise returns false.
7365 The comparison is based exclusively on the numeric Unicode values
7366 of the characters and is very fast, but is not what a human would
7367 expect. Consider sorting user-interface strings with
7368 QString::localeAwareCompare().
7372 \fn bool QLatin1String::operator<=(const char *other) const
7376 The \a other const char pointer is converted to a QString using
7377 the QString::fromAscii() function.
7379 You can disable this operator by defining \c
7380 QT_NO_CAST_FROM_ASCII when you compile your applications. This
7381 can be useful if you want to ensure that all user-visible strings
7382 go through QObject::tr(), for example.
7387 /*! \fn bool operator==(const QLatin1String &s1, const QLatin1String &s2)
7388 \relates QLatin1String
7390 Returns true if string \a s1 is lexically equal to string \a s2; otherwise
7393 /*! \fn bool operator!=(const QLatin1String &s1, const QLatin1String &s2)
7394 \relates QLatin1String
7396 Returns true if string \a s1 is lexically unequal to string \a s2; otherwise
7399 /*! \fn bool operator<(const QLatin1String &s1, const QLatin1String &s2)
7400 \relates QLatin1String
7402 Returns true if string \a s1 is lexically smaller than string \a s2; otherwise
7405 /*! \fn bool operator<=(const QLatin1String &s1, const QLatin1String &s2)
7406 \relates QLatin1String
7408 Returns true if string \a s1 is lexically smaller than or equal to string \a s2; otherwise
7411 /*! \fn bool operator>(const QLatin1String &s1, const QLatin1String &s2)
7412 \relates QLatin1String
7414 Returns true if string \a s1 is lexically greater than string \a s2; otherwise
7417 /*! \fn bool operator>=(const QLatin1String &s1, const QLatin1String &s2)
7418 \relates QLatin1String
7420 Returns true if string \a s1 is lexically greater than or equal to
7421 string \a s2; otherwise returns false.
7425 #if !defined(QT_NO_DATASTREAM) || (defined(QT_BOOTSTRAPPED) && !defined(QT_BUILD_QMAKE))
7427 \fn QDataStream &operator<<(QDataStream &stream, const QString &string)
7430 Writes the given \a string to the specified \a stream.
7432 \sa {Serializing Qt Data Types}
7435 QDataStream &operator<<(QDataStream &out, const QString &str)
7437 if (out.version() == 1) {
7438 out << str.toLatin1();
7440 if (!str.isNull() || out.version() < 3) {
7441 if ((out.byteOrder() == QDataStream::BigEndian) == (QSysInfo::ByteOrder == QSysInfo::BigEndian)) {
7442 out.writeBytes(reinterpret_cast<const char *>(str.unicode()), sizeof(QChar) * str.length());
7444 QVarLengthArray<ushort> buffer(str.length());
7445 const ushort *data = reinterpret_cast<const ushort *>(str.constData());
7446 for (int i = 0; i < str.length(); i++) {
7447 buffer[i] = qbswap(*data);
7450 out.writeBytes(reinterpret_cast<const char *>(buffer.data()), sizeof(ushort) * buffer.size());
7453 // write null marker
7454 out << (quint32)0xffffffff;
7461 \fn QDataStream &operator>>(QDataStream &stream, QString &string)
7464 Reads a string from the specified \a stream into the given \a string.
7466 \sa {Serializing Qt Data Types}
7469 QDataStream &operator>>(QDataStream &in, QString &str)
7471 #ifdef QT_QSTRING_UCS_4
7472 #if defined(Q_CC_GNU)
7473 #warning "operator>> not working properly"
7477 if (in.version() == 1) {
7480 str = QString::fromLatin1(l);
7483 in >> bytes; // read size of string
7484 if (bytes == 0xffffffff) { // null string
7486 } else if (bytes > 0) { // not empty
7489 in.setStatus(QDataStream::ReadCorruptData);
7493 const quint32 Step = 1024 * 1024;
7494 quint32 len = bytes / 2;
7495 quint32 allocated = 0;
7497 while (allocated < len) {
7498 int blockSize = qMin(Step, len - allocated);
7499 str.resize(allocated + blockSize);
7500 if (in.readRawData(reinterpret_cast<char *>(str.data()) + allocated * 2,
7501 blockSize * 2) != blockSize * 2) {
7503 in.setStatus(QDataStream::ReadPastEnd);
7506 allocated += blockSize;
7509 if ((in.byteOrder() == QDataStream::BigEndian)
7510 != (QSysInfo::ByteOrder == QSysInfo::BigEndian)) {
7511 ushort *data = reinterpret_cast<ushort *>(str.data());
7513 *data = qbswap(*data);
7518 str = QString(QLatin1String(""));
7523 #endif // QT_NO_DATASTREAM
7531 \brief The QStringRef class provides a thin wrapper around QString substrings.
7534 \ingroup string-processing
7536 QStringRef provides a read-only subset of the QString API.
7538 A string reference explicitly references a portion of a string()
7539 with a given size(), starting at a specific position(). Calling
7540 toString() returns a copy of the data as a real QString instance.
7542 This class is designed to improve the performance of substring
7543 handling when manipulating substrings obtained from existing QString
7544 instances. QStringRef avoids the memory allocation and reference
7545 counting overhead of a standard QString by simply referencing a
7546 part of the original string. This can prove to be advantageous in
7547 low level code, such as that used in a parser, at the expense of
7548 potentially more complex code.
7550 For most users, there are no semantic benefits to using QStringRef
7551 instead of QString since QStringRef requires attention to be paid
7552 to memory management issues, potentially making code more complex
7553 to write and maintain.
7555 \warning A QStringRef is only valid as long as the referenced
7556 string exists. If the original string is deleted, the string
7557 reference points to an invalid memory location.
7559 We suggest that you only use this class in stable code where profiling
7560 has clearly identified that performance improvements can be made by
7561 replacing standard string operations with the optimized substring
7562 handling provided by this class.
7564 \sa {Implicitly Shared Classes}
7569 \fn QStringRef::QStringRef()
7571 Constructs an empty string reference.
7574 /*! \fn QStringRef::QStringRef(const QString *string, int position, int length)
7576 Constructs a string reference to the range of characters in the given
7577 \a string specified by the starting \a position and \a length in characters.
7579 \warning This function exists to improve performance as much as possible,
7580 and performs no bounds checking. For program correctness, \a position and
7581 \a length must describe a valid substring of \a string.
7583 This means that the starting \a position must be positive or 0 and smaller
7584 than \a string's length, and \a length must be positive or 0 but smaller than
7585 the string's length minus the starting \a position;
7586 i.e, 0 <= position < string->length() and
7587 0 <= length <= string->length() - position must both be satisfied.
7590 /*! \fn QStringRef::QStringRef(const QString *string)
7592 Constructs a string reference to the given \a string.
7595 /*! \fn QStringRef::QStringRef(const QStringRef &other)
7597 Constructs a copy of the \a other string reference.
7600 \fn QStringRef::~QStringRef()
7602 Destroys the string reference.
7604 Since this class is only used to refer to string data, and does not take
7605 ownership of it, no memory is freed when instances are destroyed.
7610 \fn int QStringRef::position() const
7612 Returns the starting position in the referenced string that is referred to
7613 by the string reference.
7615 \sa size(), string()
7619 \fn int QStringRef::size() const
7621 Returns the number of characters referred to by the string reference.
7622 Equivalent to length() and count().
7624 \sa position(), string()
7627 \fn int QStringRef::count() const
7628 Returns the number of characters referred to by the string reference.
7629 Equivalent to size() and length().
7631 \sa position(), string()
7634 \fn int QStringRef::length() const
7635 Returns the number of characters referred to by the string reference.
7636 Equivalent to size() and count().
7638 \sa position(), string()
7643 \fn bool QStringRef::isEmpty() const
7645 Returns true if the string reference has no characters; otherwise returns
7648 A string reference is empty if its size is zero.
7654 \fn bool QStringRef::isNull() const
7656 Returns true if string() returns a null pointer or a pointer to a
7657 null string; otherwise returns true.
7663 \fn const QString *QStringRef::string() const
7665 Returns a pointer to the string referred to by the string reference, or
7666 0 if it does not reference a string.
7673 \fn const QChar *QStringRef::unicode() const
7675 Returns a Unicode representation of the string reference. Since
7676 the data stems directly from the referenced string, it is not
7677 null-terminated unless the string reference includes the string's
7684 \fn const QChar *QStringRef::data() const
7690 \fn const QChar *QStringRef::constData() const
7696 Returns a copy of the string reference as a QString object.
7698 If the string reference is not a complete reference of the string
7699 (meaning that position() is 0 and size() equals string()->size()),
7700 this function will allocate a new string to return.
7705 QString QStringRef::toString() const {
7708 if (m_size && m_position == 0 && m_size == m_string->size())
7710 return QString(m_string->unicode() + m_position, m_size);
7714 /*! \relates QStringRef
7716 Returns true if string reference \a s1 is lexically equal to string reference \a s2; otherwise
7719 bool operator==(const QStringRef &s1,const QStringRef &s2)
7720 { return (s1.size() == s2.size() &&
7721 qMemEquals((const ushort *)s1.unicode(), (const ushort *)s2.unicode(), s1.size()));
7724 /*! \relates QStringRef
7726 Returns true if string \a s1 is lexically equal to string reference \a s2; otherwise
7729 bool operator==(const QString &s1,const QStringRef &s2)
7730 { return (s1.size() == s2.size() &&
7731 qMemEquals((const ushort *)s1.unicode(), (const ushort *)s2.unicode(), s1.size()));
7734 /*! \relates QStringRef
7736 Returns true if string \a s1 is lexically equal to string reference \a s2; otherwise
7739 bool operator==(const QLatin1String &s1, const QStringRef &s2)
7741 if (s1.size() != s2.size())
7744 const ushort *uc = reinterpret_cast<const ushort *>(s2.unicode());
7745 const ushort *e = uc + s2.size();
7746 const uchar *c = reinterpret_cast<const uchar *>(s1.latin1());
7748 return s2.isEmpty();
7751 if (uc == e || *uc != *c)
7762 Returns true if string reference \a s1 is lexically less than
7763 string reference \a s2; otherwise returns false.
7765 The comparison is based exclusively on the numeric Unicode values
7766 of the characters and is very fast, but is not what a human would
7767 expect. Consider sorting user-interface strings using the
7768 QString::localeAwareCompare() function.
7770 bool operator<(const QStringRef &s1,const QStringRef &s2)
7772 return ucstrcmp(s1.constData(), s1.length(), s2.constData(), s2.length()) < 0;
7775 /*!\fn bool operator<=(const QStringRef &s1,const QStringRef &s2)
7779 Returns true if string reference \a s1 is lexically less than
7780 or equal to string reference \a s2; otherwise returns false.
7782 The comparison is based exclusively on the numeric Unicode values
7783 of the characters and is very fast, but is not what a human would
7784 expect. Consider sorting user-interface strings using the
7785 QString::localeAwareCompare() function.
7788 /*!\fn bool operator>=(const QStringRef &s1,const QStringRef &s2)
7792 Returns true if string reference \a s1 is lexically greater than
7793 or equal to string reference \a s2; otherwise returns false.
7795 The comparison is based exclusively on the numeric Unicode values
7796 of the characters and is very fast, but is not what a human would
7797 expect. Consider sorting user-interface strings using the
7798 QString::localeAwareCompare() function.
7801 /*!\fn bool operator>(const QStringRef &s1,const QStringRef &s2)
7805 Returns true if string reference \a s1 is lexically greater than
7806 string reference \a s2; otherwise returns false.
7808 The comparison is based exclusively on the numeric Unicode values
7809 of the characters and is very fast, but is not what a human would
7810 expect. Consider sorting user-interface strings using the
7811 QString::localeAwareCompare() function.
7816 \fn const QChar QStringRef::at(int position) const
7818 Returns the character at the given index \a position in the
7821 The \a position must be a valid index position in the string
7822 (i.e., 0 <= \a position < size()).
7826 \fn void QStringRef::clear()
7828 Clears the contents of the string reference by making it null and empty.
7830 \sa isEmpty(), isNull()
7834 \fn QStringRef &QStringRef::operator=(const QStringRef &other)
7836 Assigns the \a other string reference to this string reference, and
7841 \fn QStringRef &QStringRef::operator=(const QString *string)
7843 Constructs a string reference to the given \a string and assigns it to
7844 this string reference, returning the result.
7848 \typedef QString::DataPtr
7853 \fn DataPtr & QString::data_ptr()
7859 /*! Appends the string reference to \a string, and returns a new
7860 reference to the combined string data.
7862 QStringRef QStringRef::appendTo(QString *string) const
7865 return QStringRef();
7866 int pos = string->size();
7867 string->insert(pos, unicode(), size());
7868 return QStringRef(string, pos, size());
7872 \fn int QStringRef::compare(const QStringRef &s1, const QString &s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
7875 Compares the string \a s1 with the string \a s2 and returns an
7876 integer less than, equal to, or greater than zero if \a s1
7877 is less than, equal to, or greater than \a s2.
7879 If \a cs is Qt::CaseSensitive, the comparison is case sensitive;
7880 otherwise the comparison is case insensitive.
7884 \fn int QStringRef::compare(const QStringRef &s1, const QStringRef &s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
7888 Compares the string \a s1 with the string \a s2 and returns an
7889 integer less than, equal to, or greater than zero if \a s1
7890 is less than, equal to, or greater than \a s2.
7892 If \a cs is Qt::CaseSensitive, the comparison is case sensitive;
7893 otherwise the comparison is case insensitive.
7897 \fn int QStringRef::compare(const QStringRef &s1, QLatin1String s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
7901 Compares the string \a s1 with the string \a s2 and returns an
7902 integer less than, equal to, or greater than zero if \a s1
7903 is less than, equal to, or greater than \a s2.
7905 If \a cs is Qt::CaseSensitive, the comparison is case sensitive;
7906 otherwise the comparison is case insensitive.
7911 \fn int QStringRef::compare(const QString &other, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
7914 Compares this string with the \a other string and returns an
7915 integer less than, equal to, or greater than zero if this string
7916 is less than, equal to, or greater than the \a other string.
7918 If \a cs is Qt::CaseSensitive, the comparison is case sensitive;
7919 otherwise the comparison is case insensitive.
7921 Equivalent to \c {compare(*this, other, cs)}.
7923 \sa QString::compare()
7928 \fn int QStringRef::compare(const QStringRef &other, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
7931 Compares this string with the \a other string and returns an
7932 integer less than, equal to, or greater than zero if this string
7933 is less than, equal to, or greater than the \a other string.
7935 If \a cs is Qt::CaseSensitive, the comparison is case sensitive;
7936 otherwise the comparison is case insensitive.
7938 Equivalent to \c {compare(*this, other, cs)}.
7940 \sa QString::compare()
7945 \fn int QStringRef::compare(QLatin1String other, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
7948 Compares this string with the \a other string and returns an
7949 integer less than, equal to, or greater than zero if this string
7950 is less than, equal to, or greater than the \a other string.
7952 If \a cs is Qt::CaseSensitive, the comparison is case sensitive;
7953 otherwise the comparison is case insensitive.
7955 Equivalent to \c {compare(*this, other, cs)}.
7957 \sa QString::compare()
7961 \fn int QStringRef::localeAwareCompare(const QStringRef &s1, const QString & s2)
7964 Compares \a s1 with \a s2 and returns an integer less than, equal
7965 to, or greater than zero if \a s1 is less than, equal to, or
7968 The comparison is performed in a locale- and also
7969 platform-dependent manner. Use this function to present sorted
7970 lists of strings to the user.
7972 On Mac OS X, this function compares according the
7973 "Order for sorted lists" setting in the International prefereces panel.
7975 \sa compare(), QTextCodec::locale()
7979 \fn int QStringRef::localeAwareCompare(const QStringRef &s1, const QStringRef & s2)
7983 Compares \a s1 with \a s2 and returns an integer less than, equal
7984 to, or greater than zero if \a s1 is less than, equal to, or
7987 The comparison is performed in a locale- and also
7988 platform-dependent manner. Use this function to present sorted
7989 lists of strings to the user.
7994 \fn int QStringRef::localeAwareCompare(const QString &other) const
7998 Compares this string with the \a other string and returns an
7999 integer less than, equal to, or greater than zero if this string
8000 is less than, equal to, or greater than the \a other string.
8002 The comparison is performed in a locale- and also
8003 platform-dependent manner. Use this function to present sorted
8004 lists of strings to the user.
8008 \fn int QStringRef::localeAwareCompare(const QStringRef &other) const
8012 Compares this string with the \a other string and returns an
8013 integer less than, equal to, or greater than zero if this string
8014 is less than, equal to, or greater than the \a other string.
8016 The comparison is performed in a locale- and also
8017 platform-dependent manner. Use this function to present sorted
8018 lists of strings to the user.
8022 \fn QString &QString::append(const QStringRef &reference)
8025 Appends the given string \a reference to this string and returns the result.
8027 QString &QString::append(const QStringRef &str)
8029 if (str.string() == this) {
8031 } else if (str.string()) {
8032 int oldSize = size();
8033 resize(oldSize + str.size());
8034 memcpy(data() + oldSize, str.unicode(), str.size() * sizeof(QChar));
8042 Returns a substring reference to the \a n leftmost characters
8045 If \a n is greater than size() or less than zero, a reference to the entire
8048 \snippet doc/src/snippets/qstring/main.cpp leftRef
8050 \sa left(), rightRef(), midRef(), startsWith()
8052 QStringRef QString::leftRef(int n) const
8054 if (n >= d->size || n < 0)
8056 return QStringRef(this, 0, n);
8062 Returns a substring reference to the \a n rightmost characters
8065 If \a n is greater than size() or less than zero, a reference to the entire
8068 \snippet doc/src/snippets/qstring/main.cpp rightRef
8070 \sa right(), leftRef(), midRef(), endsWith()
8072 QStringRef QString::rightRef(int n) const
8074 if (n >= d->size || n < 0)
8076 return QStringRef(this, d->size - n, n);
8082 Returns a substring reference to \a n characters of this string,
8083 starting at the specified \a position.
8085 If the \a position exceeds the length of the string, a null
8086 reference is returned.
8088 If there are less than \a n characters available in the string,
8089 starting at the given \a position, or if \a n is -1 (default), the
8090 function returns all characters from the specified \a position
8095 \snippet doc/src/snippets/qstring/main.cpp midRef
8097 \sa mid(), leftRef(), rightRef()
8100 QStringRef QString::midRef(int position, int n) const
8102 if (d == &shared_null.str || position > d->size)
8103 return QStringRef();
8105 n = d->size - position;
8110 if (n + position > d->size)
8111 n = d->size - position;
8112 return QStringRef(this, position, n);
8118 Returns the index position of the first occurrence of the string \a
8119 str in this string reference, searching forward from index position
8120 \a from. Returns -1 if \a str is not found.
8122 If \a cs is Qt::CaseSensitive (default), the search is case
8123 sensitive; otherwise the search is case insensitive.
8125 If \a from is -1, the search starts at the last character; if it is
8126 -2, at the next to last character and so on.
8128 \sa QString::indexOf(), lastIndexOf(), contains(), count()
8130 int QStringRef::indexOf(const QString &str, int from, Qt::CaseSensitivity cs) const
8132 return qFindString(unicode(), length(), from, str.unicode(), str.length(), cs);
8139 Returns the index position of the first occurrence of the
8140 character \a ch in the string reference, searching forward from
8141 index position \a from. Returns -1 if \a ch could not be found.
8143 \sa QString::indexOf(), lastIndexOf(), contains(), count()
8145 int QStringRef::indexOf(QChar ch, int from, Qt::CaseSensitivity cs) const
8147 return findChar(unicode(), length(), ch, from, cs);
8153 Returns the index position of the first occurrence of the string \a
8154 str in this string reference, searching forward from index position
8155 \a from. Returns -1 if \a str is not found.
8157 If \a cs is Qt::CaseSensitive (default), the search is case
8158 sensitive; otherwise the search is case insensitive.
8160 If \a from is -1, the search starts at the last character; if it is
8161 -2, at the next to last character and so on.
8163 \sa QString::indexOf(), lastIndexOf(), contains(), count()
8165 int QStringRef::indexOf(QLatin1String str, int from, Qt::CaseSensitivity cs) const
8167 return qt_find_latin1_string(unicode(), size(), str, from, cs);
8175 Returns the index position of the first occurrence of the string
8176 reference \a str in this string reference, searching forward from
8177 index position \a from. Returns -1 if \a str is not found.
8179 If \a cs is Qt::CaseSensitive (default), the search is case
8180 sensitive; otherwise the search is case insensitive.
8182 \sa QString::indexOf(), lastIndexOf(), contains(), count()
8184 int QStringRef::indexOf(const QStringRef &str, int from, Qt::CaseSensitivity cs) const
8186 return qFindString(unicode(), size(), from, str.unicode(), str.size(), cs);
8192 Returns the index position of the last occurrence of the string \a
8193 str in this string reference, searching backward from index position
8194 \a from. If \a from is -1 (default), the search starts at the last
8195 character; if \a from is -2, at the next to last character and so
8196 on. Returns -1 if \a str is not found.
8198 If \a cs is Qt::CaseSensitive (default), the search is case
8199 sensitive; otherwise the search is case insensitive.
8201 \sa QString::lastIndexOf(), indexOf(), contains(), count()
8203 int QStringRef::lastIndexOf(const QString &str, int from, Qt::CaseSensitivity cs) const
8205 const int sl = str.size();
8207 return lastIndexOf(str.at(0), from, cs);
8209 const int l = size();;
8213 if (from == l && sl == 0)
8215 if (from < 0 || from >= l || delta < 0)
8220 return lastIndexOfHelper(reinterpret_cast<const ushort*>(unicode()), from,
8221 reinterpret_cast<const ushort*>(str.unicode()), str.size(), cs);
8226 \overload lastIndexOf()
8228 Returns the index position of the last occurrence of the character
8229 \a ch, searching backward from position \a from.
8231 \sa QString::lastIndexOf(), indexOf(), contains(), count()
8233 int QStringRef::lastIndexOf(QChar ch, int from, Qt::CaseSensitivity cs) const
8235 return qt_last_index_of(unicode(), size(), ch, from, cs);
8240 \overload lastIndexOf()
8242 Returns the index position of the last occurrence of the string \a
8243 str in this string reference, searching backward from index position
8244 \a from. If \a from is -1 (default), the search starts at the last
8245 character; if \a from is -2, at the next to last character and so
8246 on. Returns -1 if \a str is not found.
8248 If \a cs is Qt::CaseSensitive (default), the search is case
8249 sensitive; otherwise the search is case insensitive.
8251 \sa QString::lastIndexOf(), indexOf(), contains(), count()
8253 int QStringRef::lastIndexOf(QLatin1String str, int from, Qt::CaseSensitivity cs) const
8255 const int sl = str.size();
8257 return lastIndexOf(QLatin1Char(str.latin1()[0]), from, cs);
8259 const int l = size();
8263 if (from == l && sl == 0)
8265 if (from < 0 || from >= l || delta < 0)
8270 QVarLengthArray<ushort> s(sl);
8271 for (int i = 0; i < sl; ++i)
8272 s[i] = str.latin1()[i];
8274 return lastIndexOfHelper(reinterpret_cast<const ushort*>(unicode()), from, s.data(), sl, cs);
8279 \overload lastIndexOf()
8281 Returns the index position of the last occurrence of the string
8282 reference \a str in this string reference, searching backward from
8283 index position \a from. If \a from is -1 (default), the search
8284 starts at the last character; if \a from is -2, at the next to last
8285 character and so on. Returns -1 if \a str is not found.
8287 If \a cs is Qt::CaseSensitive (default), the search is case
8288 sensitive; otherwise the search is case insensitive.
8290 \sa QString::lastIndexOf(), indexOf(), contains(), count()
8292 int QStringRef::lastIndexOf(const QStringRef &str, int from, Qt::CaseSensitivity cs) const
8294 const int sl = str.size();
8296 return lastIndexOf(str.at(0), from, cs);
8298 const int l = size();
8302 if (from == l && sl == 0)
8304 if (from < 0 || from >= l || delta < 0)
8309 return lastIndexOfHelper(reinterpret_cast<const ushort*>(unicode()), from,
8310 reinterpret_cast<const ushort*>(str.unicode()),
8316 Returns the number of (potentially overlapping) occurrences of
8317 the string \a str in this string reference.
8319 If \a cs is Qt::CaseSensitive (default), the search is
8320 case sensitive; otherwise the search is case insensitive.
8322 \sa QString::count(), contains(), indexOf()
8324 int QStringRef::count(const QString &str, Qt::CaseSensitivity cs) const
8326 return qt_string_count(unicode(), size(), str.unicode(), str.size(), cs);
8333 Returns the number of occurrences of the character \a ch in the
8336 If \a cs is Qt::CaseSensitive (default), the search is
8337 case sensitive; otherwise the search is case insensitive.
8339 \sa QString::count(), contains(), indexOf()
8341 int QStringRef::count(QChar ch, Qt::CaseSensitivity cs) const
8343 return qt_string_count(unicode(), size(), ch, cs);
8350 Returns the number of (potentially overlapping) occurrences of the
8351 string reference \a str in this string reference.
8353 If \a cs is Qt::CaseSensitive (default), the search is
8354 case sensitive; otherwise the search is case insensitive.
8356 \sa QString::count(), contains(), indexOf()
8358 int QStringRef::count(const QStringRef &str, Qt::CaseSensitivity cs) const
8360 return qt_string_count(unicode(), size(), str.unicode(), str.size(), cs);
8366 Returns true if the string reference starts with \a str; otherwise
8369 If \a cs is Qt::CaseSensitive (default), the search is
8370 case sensitive; otherwise the search is case insensitive.
8372 \sa QString::startsWith(), endsWith()
8374 bool QStringRef::startsWith(const QString &str, Qt::CaseSensitivity cs) const
8376 return qt_starts_with(isNull() ? 0 : unicode(), size(),
8377 str.isNull() ? 0 : str.unicode(), str.size(), cs);
8382 \overload startsWith()
8383 \sa QString::startsWith(), endsWith()
8385 bool QStringRef::startsWith(QLatin1String str, Qt::CaseSensitivity cs) const
8387 return qt_starts_with(isNull() ? 0 : unicode(), size(), str, cs);
8392 \overload startsWith()
8393 \sa QString::startsWith(), endsWith()
8395 bool QStringRef::startsWith(const QStringRef &str, Qt::CaseSensitivity cs) const
8397 return qt_starts_with(isNull() ? 0 : unicode(), size(),
8398 str.isNull() ? 0 : str.unicode(), str.size(), cs);
8403 \overload startsWith()
8405 Returns true if the string reference starts with \a ch; otherwise
8408 If \a cs is Qt::CaseSensitive (default), the search is case
8409 sensitive; otherwise the search is case insensitive.
8411 \sa QString::startsWith(), endsWith()
8413 bool QStringRef::startsWith(QChar ch, Qt::CaseSensitivity cs) const
8416 const ushort *data = reinterpret_cast<const ushort*>(unicode());
8417 return (cs == Qt::CaseSensitive
8419 : foldCase(data[0]) == foldCase(ch.unicode()));
8427 Returns true if the string reference ends with \a str; otherwise
8430 If \a cs is Qt::CaseSensitive (default), the search is case
8431 sensitive; otherwise the search is case insensitive.
8433 \sa QString::endsWith(), startsWith()
8435 bool QStringRef::endsWith(const QString &str, Qt::CaseSensitivity cs) const
8437 return qt_ends_with(isNull() ? 0 : unicode(), size(),
8438 str.isNull() ? 0 : str.unicode(), str.size(), cs);
8443 \overload endsWith()
8445 Returns true if the string reference ends with \a ch; otherwise
8448 If \a cs is Qt::CaseSensitive (default), the search is case
8449 sensitive; otherwise the search is case insensitive.
8451 \sa QString::endsWith(), endsWith()
8453 bool QStringRef::endsWith(QChar ch, Qt::CaseSensitivity cs) const
8456 const ushort *data = reinterpret_cast<const ushort*>(unicode());
8457 const int size = length();
8458 return (cs == Qt::CaseSensitive
8459 ? data[size - 1] == ch
8460 : foldCase(data[size - 1]) == foldCase(ch.unicode()));
8468 \overload endsWith()
8469 \sa QString::endsWith(), endsWith()
8471 bool QStringRef::endsWith(QLatin1String str, Qt::CaseSensitivity cs) const
8473 return qt_ends_with(isNull() ? 0 : unicode(), size(), str, cs);
8478 \overload endsWith()
8479 \sa QString::endsWith(), endsWith()
8481 bool QStringRef::endsWith(const QStringRef &str, Qt::CaseSensitivity cs) const
8483 return qt_ends_with(isNull() ? 0 : unicode(), size(),
8484 str.isNull() ? 0 : str.unicode(), str.size(), cs);
8488 /*! \fn bool QStringRef::contains(const QString &str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
8491 Returns true if this string reference contains an occurrence of
8492 the string \a str; otherwise returns false.
8494 If \a cs is Qt::CaseSensitive (default), the search is
8495 case sensitive; otherwise the search is case insensitive.
8497 \sa indexOf(), count()
8500 /*! \fn bool QStringRef::contains(QChar ch, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
8502 \overload contains()
8505 Returns true if this string contains an occurrence of the
8506 character \a ch; otherwise returns false.
8508 If \a cs is Qt::CaseSensitive (default), the search is
8509 case sensitive; otherwise the search is case insensitive.
8513 /*! \fn bool QStringRef::contains(const QStringRef &str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
8514 \overload contains()
8517 Returns true if this string reference contains an occurrence of
8518 the string reference \a str; otherwise returns false.
8520 If \a cs is Qt::CaseSensitive (default), the search is
8521 case sensitive; otherwise the search is case insensitive.
8523 \sa indexOf(), count()
8526 /*! \fn bool QStringRef::contains(QLatin1String str, Qt::CaseSensitivity cs) const
8528 \overload contains()
8530 Returns true if this string reference contains an occurrence of
8531 the string \a str; otherwise returns false.
8533 If \a cs is Qt::CaseSensitive (default), the search is
8534 case sensitive; otherwise the search is case insensitive.
8536 \sa indexOf(), count()
8539 static inline int qt_last_index_of(const QChar *haystack, int haystackLen, QChar needle,
8540 int from, Qt::CaseSensitivity cs)
8542 ushort c = needle.unicode();
8544 from += haystackLen;
8545 if (from < 0 || from >= haystackLen)
8548 const ushort *b = reinterpret_cast<const ushort*>(haystack);
8549 const ushort *n = b + from;
8550 if (cs == Qt::CaseSensitive) {
8557 if (foldCase(*n) == c)
8566 static inline int qt_string_count(const QChar *haystack, int haystackLen,
8567 const QChar *needle, int needleLen,
8568 Qt::CaseSensitivity cs)
8572 if (haystackLen > 500 && needleLen > 5) {
8573 QStringMatcher matcher(needle, needleLen, cs);
8574 while ((i = matcher.indexIn(haystack, haystackLen, i + 1)) != -1)
8577 while ((i = qFindString(haystack, haystackLen, i + 1, needle, needleLen, cs)) != -1)
8583 static inline int qt_string_count(const QChar *unicode, int size, QChar ch,
8584 Qt::CaseSensitivity cs)
8586 ushort c = ch.unicode();
8588 const ushort *b = reinterpret_cast<const ushort*>(unicode);
8589 const ushort *i = b + size;
8590 if (cs == Qt::CaseSensitive) {
8597 if (foldCase(*(--i)) == c)
8603 static inline int qt_find_latin1_string(const QChar *haystack, int size,
8604 const QLatin1String &needle,
8605 int from, Qt::CaseSensitivity cs)
8607 const char *latin1 = needle.latin1();
8608 int len = needle.size();
8609 QVarLengthArray<ushort> s(len);
8610 for (int i = 0; i < len; ++i)
8613 return qFindString(haystack, size, from,
8614 reinterpret_cast<const QChar*>(s.constData()), len, cs);
8617 static inline bool qt_starts_with(const QChar *haystack, int haystackLen,
8618 const QChar *needle, int needleLen, Qt::CaseSensitivity cs)
8622 if (haystackLen == 0)
8623 return needleLen == 0;
8624 if (needleLen > haystackLen)
8627 const ushort *h = reinterpret_cast<const ushort*>(haystack);
8628 const ushort *n = reinterpret_cast<const ushort*>(needle);
8630 if (cs == Qt::CaseSensitive) {
8631 return qMemEquals(h, n, needleLen);
8635 for (int i = 0; i < needleLen; ++i)
8636 if (foldCase(h[i], last) != foldCase(n[i], olast))
8642 static inline bool qt_starts_with(const QChar *haystack, int haystackLen,
8643 const QLatin1String &needle, Qt::CaseSensitivity cs)
8646 return !needle.latin1();
8647 if (haystackLen == 0)
8648 return !needle.latin1() || *needle.latin1() == 0;
8649 const int slen = needle.size();
8650 if (slen > haystackLen)
8652 const ushort *data = reinterpret_cast<const ushort*>(haystack);
8653 const uchar *latin = reinterpret_cast<const uchar*>(needle.latin1());
8654 if (cs == Qt::CaseSensitive) {
8655 for (int i = 0; i < slen; ++i)
8656 if (data[i] != latin[i])
8659 for (int i = 0; i < slen; ++i)
8660 if (foldCase(data[i]) != foldCase((ushort)latin[i]))
8666 static inline bool qt_ends_with(const QChar *haystack, int haystackLen,
8667 const QChar *needle, int needleLen, Qt::CaseSensitivity cs)
8671 if (haystackLen == 0)
8672 return needleLen == 0;
8673 const int pos = haystackLen - needleLen;
8677 const ushort *h = reinterpret_cast<const ushort*>(haystack);
8678 const ushort *n = reinterpret_cast<const ushort*>(needle);
8680 if (cs == Qt::CaseSensitive) {
8681 return qMemEquals(h + pos, n, needleLen);
8685 for (int i = 0; i < needleLen; i++)
8686 if (foldCase(h[pos+i], last) != foldCase(n[i], olast))
8693 static inline bool qt_ends_with(const QChar *haystack, int haystackLen,
8694 const QLatin1String &needle, Qt::CaseSensitivity cs)
8697 return !needle.latin1();
8698 if (haystackLen == 0)
8699 return !needle.latin1() || *needle.latin1() == 0;
8700 const int slen = needle.size();
8701 int pos = haystackLen - slen;
8704 const uchar *latin = reinterpret_cast<const uchar*>(needle.latin1());
8705 const ushort *data = reinterpret_cast<const ushort*>(haystack);
8706 if (cs == Qt::CaseSensitive) {
8707 for (int i = 0; i < slen; i++)
8708 if (data[pos+i] != latin[i])
8711 for (int i = 0; i < slen; i++)
8712 if (foldCase(data[pos+i]) != foldCase((ushort)latin[i]))
8721 Returns a Latin-1 representation of the string as a QByteArray.
8723 The returned byte array is undefined if the string contains non-Latin1
8724 characters. Those characters may be suppressed or replaced with a
8727 \sa toAscii(), toUtf8(), toLocal8Bit(), QTextCodec
8729 QByteArray QStringRef::toLatin1() const
8731 return toLatin1_helper(unicode(), length());
8737 Returns an 8-bit representation of the string as a QByteArray.
8739 If a codec has been set using QTextCodec::setCodecForCStrings(),
8740 it is used to convert Unicode to 8-bit char; otherwise this
8741 function does the same as toLatin1().
8743 Note that, despite the name, this function does not necessarily return an US-ASCII
8744 (ANSI X3.4-1986) string and its result may not be US-ASCII compatible.
8746 \sa toLatin1(), toUtf8(), toLocal8Bit(), QTextCodec
8748 QByteArray QStringRef::toAscii() const
8750 #ifndef QT_NO_TEXTCODEC
8751 if (QString::codecForCStrings)
8752 return QString::codecForCStrings->fromUnicode(unicode(), length());
8753 #endif // QT_NO_TEXTCODEC
8760 Returns the local 8-bit representation of the string as a
8761 QByteArray. The returned byte array is undefined if the string
8762 contains characters not supported by the local 8-bit encoding.
8764 QTextCodec::codecForLocale() is used to perform the conversion from
8765 Unicode. If the locale encoding could not be determined, this function
8766 does the same as toLatin1().
8768 If this string contains any characters that cannot be encoded in the
8769 locale, the returned byte array is undefined. Those characters may be
8770 suppressed or replaced by another.
8772 \sa toAscii(), toLatin1(), toUtf8(), QTextCodec
8774 QByteArray QStringRef::toLocal8Bit() const
8776 #ifndef QT_NO_TEXTCODEC
8777 if (QTextCodec::codecForLocale())
8778 return QTextCodec::codecForLocale()->fromUnicode(unicode(), length());
8779 #endif // QT_NO_TEXTCODEC
8786 Returns a UTF-8 representation of the string as a QByteArray.
8788 UTF-8 is a Unicode codec and can represent all characters in a Unicode
8789 string like QString.
8791 However, in the Unicode range, there are certain codepoints that are not
8792 considered characters. The Unicode standard reserves the last two
8793 codepoints in each Unicode Plane (U+FFFE, U+FFFF, U+1FFFE, U+1FFFF,
8794 U+2FFFE, etc.), as well as 16 codepoints in the range U+FDD0..U+FDDF,
8795 inclusive, as non-characters. If any of those appear in the string, they
8796 may be discarded and will not appear in the UTF-8 representation, or they
8797 may be replaced by one or more replacement characters.
8799 \sa toAscii(), toLatin1(), toLocal8Bit(), QTextCodec
8801 QByteArray QStringRef::toUtf8() const
8804 return QByteArray();
8806 return QUtf8::convertFromUnicode(constData(), length(), 0);
8812 Returns a UCS-4/UTF-32 representation of the string as a QVector<uint>.
8814 UCS-4 is a Unicode codec and is lossless. All characters from this string
8815 can be encoded in UCS-4.
8817 \sa toAscii(), toLatin1(), toLocal8Bit(), QTextCodec
8819 QVector<uint> QStringRef::toUcs4() const
8821 QVector<uint> v(length());
8823 int len = QString::toUcs4_helper(reinterpret_cast<const ushort *>(unicode()), length(), a);
8831 \fn QString Qt::escape(const QString &plain)
8833 \sa QString::toHtmlEscaped()
8837 Converts the plain text string \a plain to a HTML string with
8838 HTML metacharacters \c{<}, \c{>}, \c{&}, and \c{"} replaced by HTML
8843 \snippet doc/src/snippets/code/src_corelib_tools_qstring.cpp 7
8845 QString QString::toHtmlEscaped() const
8848 const int len = length();
8849 rich.reserve(int(len * 1.1));
8850 for (int i = 0; i < len; ++i) {
8851 if (at(i) == QLatin1Char('<'))
8852 rich += QLatin1String("<");
8853 else if (at(i) == QLatin1Char('>'))
8854 rich += QLatin1String(">");
8855 else if (at(i) == QLatin1Char('&'))
8856 rich += QLatin1String("&");
8857 else if (at(i) == QLatin1Char('"'))
8858 rich += QLatin1String(""");
8867 \macro QStringLiteral(str)
8870 The macro generates the data for a QString out of \a str at compile time if the compiler supports it.
8871 Creating a QString from it is free in this case, and the generated string data is stored in
8872 the read-only segment of the compiled object file.
8874 For compilers not supporting the creation of compile time strings, QStringLiteral will fall back to
8877 The result of the QStringLiteral expression can be cast into a QString.
8879 If you have code looking like:
8881 if (node.hasAttribute("http-contents-length")) //...
8883 One temporary QString will be created to be passed as the hasAttribute function parameter.
8884 This can be quite expensive, as it involves a memory allocation and the copy and the conversion
8885 of the data into QString's internal encoding.
8887 This can be avoided by doing
8889 if (node.hasAttribute(QStringLiteral("http-contents-length"))) //...
8891 Then the QString's internal data will be generated at compile time and no conversion or allocation
8892 will occur at runtime
8894 Using QStringLiteral instead of a double quoted ascii literal can significantly speed up creation
8895 of QString's from data known at compile time.
8897 If the compiler is C++11 enabled the string \a str can actually contain unicode data.
8899 \note There are still a few cases in which QLatin1String is more efficient than QStringLiteral:
8900 If it is passed to a function that has an overload that takes the QLatin1String directly, without
8901 conversion to QString. For instance, this is the case of QString::operator==
8903 if (attribute.name() == QLatin1String("http-contents-length")) //...