Remove constructors taking implicit string sizes
[profile/ivi/qtbase.git] / src / corelib / tools / qstring.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the QtCore module of the Qt Toolkit.
7 **
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.
16 **
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.
20 **
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.
28 **
29 ** Other Usage
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.
32 **
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "qstringlist.h"
43 #include "qregexp.h"
44 #include "qunicodetables_p.h"
45 #ifndef QT_NO_TEXTCODEC
46 #include <qtextcodec.h>
47 #endif
48 #include <private/qutfcodec_p.h>
49 #include "qsimd_p.h"
50 #include <qdatastream.h>
51 #include <qlist.h>
52 #include "qlocale.h"
53 #include "qlocale_p.h"
54 #include "qstringmatcher.h"
55 #include "qvarlengtharray.h"
56 #include "qtools_p.h"
57 #include "qhash.h"
58 #include "qdebug.h"
59 #include "qendian.h"
60
61 #ifdef Q_OS_MAC
62 #include <private/qcore_mac_p.h>
63 #endif
64
65 #include <private/qfunctions_p.h>
66
67 #include <limits.h>
68 #include <string.h>
69 #include <stdlib.h>
70 #include <stdio.h>
71 #include <stdarg.h>
72
73 #include "qchar.cpp"
74 #include "qstringmatcher.cpp"
75
76 #ifdef Q_OS_WIN
77 #  include <qt_windows.h>
78 #  ifdef Q_OS_WINCE
79 #    include <winnls.h>
80 #  endif
81 #endif
82
83 #ifdef truncate
84 #  undef truncate
85 #endif
86
87 #ifndef LLONG_MAX
88 #define LLONG_MAX qint64_C(9223372036854775807)
89 #endif
90 #ifndef LLONG_MIN
91 #define LLONG_MIN (-LLONG_MAX - qint64_C(1))
92 #endif
93 #ifndef ULLONG_MAX
94 #define ULLONG_MAX quint64_C(18446744073709551615)
95 #endif
96
97 QT_BEGIN_NAMESPACE
98
99 #ifndef QT_NO_TEXTCODEC
100 QTextCodec *QString::codecForCStrings;
101 #endif
102
103 #ifdef QT_USE_ICU
104 // qlocale_icu.cpp
105 extern bool qt_ucol_strcoll(const QChar *source, int sourceLength, const QChar *target, int targetLength, int *result);
106 #endif
107
108
109 // internal
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);
131
132 // Unicode case-insensitive comparison
133 static int ucstricmp(const ushort *a, const ushort *ae, const ushort *b, const ushort *be)
134 {
135     if (a == b)
136         return (ae - be);
137     if (a == 0)
138         return 1;
139     if (b == 0)
140         return -1;
141
142     const ushort *e = ae;
143     if (be - b < ae - a)
144         e = a + (be - b);
145
146     uint alast = 0;
147     uint blast = 0;
148     while (a < e) {
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);
153         if ((diff))
154             return diff;
155         ++a;
156         ++b;
157     }
158     if (a == ae) {
159         if (b == be)
160             return 0;
161         return -1;
162     }
163     return 1;
164 }
165
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)
168 {
169     if (a == 0) {
170         if (b == 0)
171             return 0;
172         return 1;
173     }
174     if (b == 0)
175         return -1;
176
177     const ushort *e = ae;
178     if (be - b < ae - a)
179         e = a + (be - b);
180
181     while (a < e) {
182         int diff = foldCase(*a) - foldCase(*b);
183         if ((diff))
184             return diff;
185         ++a;
186         ++b;
187     }
188     if (a == ae) {
189         if (b == be)
190             return 0;
191         return -1;
192     }
193     return 1;
194 }
195
196 // Unicode case-sensitive compare two same-sized strings
197 static int ucstrncmp(const QChar *a, const QChar *b, int l)
198 {
199     while (l-- && *a == *b)
200         a++,b++;
201     if (l==-1)
202         return 0;
203     return a->unicode() - b->unicode();
204 }
205
206 // Unicode case-sensitive comparison
207 static int ucstrcmp(const QChar *a, int alen, const QChar *b, int blen)
208 {
209     if (a == b && alen == blen)
210         return 0;
211     int l = qMin(alen, blen);
212     int cmp = ucstrncmp(a, b, l);
213     return cmp ? cmp : (alen-blen);
214 }
215
216 // Unicode case-insensitive compare two same-sized strings
217 static int ucstrnicmp(const ushort *a, const ushort *b, int l)
218 {
219     return ucstricmp(a, a + l, b, b + l);
220 }
221
222 // Benchmarking indicates that doing memcmp is much slower than
223 // executing the comparison ourselves.
224 //
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
227 // Linux) was:
228 //
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
243 //
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.
246 //
247 // The profile on 64-bit will be different since offsetof(array, QString::Data) == 26.
248 //
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
256 //
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
264 //
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.
268
269 static bool qMemEquals(const quint16 *a, const quint16 *b, int length)
270 {
271     if (a == b || !length)
272         return true;
273
274     register union {
275         const quint16 *w;
276         const quint32 *d;
277         quintptr value;
278     } sa, sb;
279     sa.w = a;
280     sb.w = b;
281
282     // check alignment
283     if ((sa.value & 2) == (sb.value & 2)) {
284         // both addresses have the same alignment
285         if (sa.value & 2) {
286             // both addresses are not aligned to 4-bytes boundaries
287             // compare the first character
288             if (*sa.w != *sb.w)
289                 return false;
290             --length;
291             ++sa.w;
292             ++sb.w;
293
294             // now both addresses are 4-bytes aligned
295         }
296
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) {
301             if (*sa.d != *sb.d)
302                 return false;
303         }
304
305         // do we have a tail?
306         return (length & 1) ? *sa.w == *sb.w : true;
307     } else {
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) {
311             if (*sa.w != *sb.w)
312                 return false;
313         }
314     }
315     return true;
316 }
317
318 /*!
319     \internal
320
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.
325 */
326 static int findChar(const QChar *str, int len, QChar ch, int from,
327     Qt::CaseSensitivity cs)
328 {
329     const ushort *s = (const ushort *)str;
330     ushort c = ch.unicode();
331     if (from < 0)
332         from = qMax(from + len, 0);
333     if (from < len) {
334         const ushort *n = s + from - 1;
335         const ushort *e = s + len;
336         if (cs == Qt::CaseSensitive) {
337             while (++n != e)
338                 if (*n == c)
339                     return  n - s;
340         } else {
341             c = foldCase(c);
342             while (++n != e)
343                 if (foldCase(*n) == c)
344                     return  n - s;
345         }
346     }
347     return -1;
348 }
349
350 #define REHASH(a) \
351     if (sl_minus_1 < (int)sizeof(int) * CHAR_BIT)       \
352         hashHaystack -= (a) << sl_minus_1; \
353     hashHaystack <<= 1
354
355 inline bool qIsUpper(char ch)
356 {
357     return ch >= 'A' && ch <= 'Z';
358 }
359
360 inline bool qIsDigit(char ch)
361 {
362     return ch >= '0' && ch <= '9';
363 }
364
365 inline char qToLower(char ch)
366 {
367     if (ch >= 'A' && ch <= 'Z')
368         return ch - 'A' + 'a';
369     else
370         return ch;
371 }
372
373 const QString::Null QString::null = { };
374
375 /*!
376   \macro QT_NO_CAST_FROM_ASCII
377   \relates QString
378
379   Disables automatic conversions from 8-bit strings (char *) to unicode QStrings
380
381   \sa QT_NO_CAST_TO_ASCII, QT_NO_CAST_FROM_BYTEARRAY
382 */
383
384 /*!
385   \macro QT_NO_CAST_TO_ASCII
386   \relates QString
387
388   disables automatic conversion from QString to 8-bit strings (char *)
389
390   \sa QT_NO_CAST_FROM_ASCII, QT_NO_CAST_FROM_BYTEARRAY
391 */
392
393 /*!
394   \macro QT_ASCII_CAST_WARNINGS
395   \internal
396   \relates QString
397
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.
400
401   Note: This only works for compilers that support warnings for
402   deprecated API.
403
404   \sa QT_NO_CAST_TO_ASCII, QT_NO_CAST_FROM_ASCII
405 */
406
407 /*!
408     \class QCharRef
409     \reentrant
410     \brief The QCharRef class is a helper class for QString.
411
412     \internal
413
414     \ingroup string-processing
415
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.
421
422     Most of the QChar member functions also exist in QCharRef.
423     However, they are not explicitly documented here.
424
425     \sa QString::operator[]() QString::at() QChar
426 */
427
428 /*!
429     \class QString
430     \reentrant
431
432     \brief The QString class provides a Unicode character string.
433
434     \ingroup tools
435     \ingroup shared
436     \ingroup string-processing
437
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.)
442
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.
447
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.
452
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}).
462
463     \tableofcontents
464
465     \section1 Initializing a String
466
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":
470
471     \snippet doc/src/snippets/qstring/main.cpp 0
472
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().
477
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.
482
483     You can also provide string data as an array of \l{QChar}s:
484
485     \snippet doc/src/snippets/qstring/main.cpp 1
486
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.)
491
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
498     example:
499
500     \snippet doc/src/snippets/qstring/main.cpp 2
501
502     For read-only access, an alternative syntax is to use the at()
503     function:
504
505     \snippet doc/src/snippets/qstring/main.cpp 3
506
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
510     at a time.
511
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.
515
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.
519
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:
523
524     \snippet doc/src/snippets/qstring/main.cpp 4
525
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().
532
533     \section1 Manipulating String Data
534
535     QString provides the following basic functions for modifying the
536     character data: append(), prepend(), insert(), replace(), and
537     remove(). For example:
538
539     \snippet doc/src/snippets/qstring/main.cpp 5
540
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.
546
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
551     replace() overloads.
552
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().
559
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:
567
568     \snippet doc/src/snippets/qstring/main.cpp 6
569
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.
574
575     To get an upper- or lowercase version of a string use toUpper() or
576     toLower().
577
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()
584     function.
585
586     \section1 Querying String Data
587
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
593     string, use count().
594
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.
601
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.
606
607     \section1 Converting Between 8-Bit Strings and Unicode Strings
608
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().
612
613     \list
614     \o toAscii() returns an 8-bit string encoded using the codec
615        specified by QTextCodec::codecForCStrings (by default, that is
616        Latin 1).
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
622        encoding.
623     \endlist
624
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.
628
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:
637
638     \list
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
642        to C strings.
643     \endlist
644
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}:
648
649     \snippet doc/src/snippets/code/src_corelib_tools_qstring.cpp 0
650
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
654     example:
655
656     \snippet doc/src/snippets/code/src_corelib_tools_qstring.cpp 1
657
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
661     class.)
662
663     \table 100 %
664     \header
665     \o Note for C Programmers
666
667     \row
668     \o
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:
672
673     \snippet doc/src/snippets/qstring/main.cpp 7
674
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
679     sharing.
680
681     \endtable
682
683     \section1 Distinction Between Null and Empty Strings
684
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:
691
692     \snippet doc/src/snippets/qstring/main.cpp 8
693
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().
699
700     \section1 Argument Formats
701
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
704     following:
705
706     \table
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
713     \endtable
714
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).
720
721     \section1 More Efficient String Construction
722
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.
729
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.
734
735     Using the QString \c{'+'} operator, it is easy to construct a
736     complex string from multiple substrings. You will often write code
737     like this:
738
739     \snippet doc/src/snippets/qstring/stringbuilder.cpp 0
740
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.
744
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
748     memory allocator.
749
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
756     look at it.
757
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.
766
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
770     test).
771
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:
776
777     \snippet doc/src/snippets/qstring/stringbuilder.cpp 5
778
779     A more global approach which is the most convenient but
780     not entirely source compatible, is to this define in your
781     .pro file:
782
783     \snippet doc/src/snippets/qstring/stringbuilder.cpp 3
784
785     and the \c{'+'} will automatically be performed as the
786     \c{QStringBuilder} \c{'%'} everywhere.
787
788     \sa fromRawData(), QChar, QLatin1String, QByteArray, QStringRef
789 */
790
791 /*!
792     \enum QString::SplitBehavior
793
794     This enum specifies how the split() function should behave with
795     respect to empty strings.
796
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.
799
800     \sa split()
801 */
802
803 const QStaticStringData<1> QString::shared_null = { { Q_REFCOUNT_INITIALIZE_STATIC, 0, 0, false, { 0 } }, { 0 } };
804 const QStaticStringData<1> QString::shared_empty = { { Q_REFCOUNT_INITIALIZE_STATIC, 0, 0, false, { 0 } }, { 0 } };
805
806 int QString::grow(int size)
807 {
808     return qAllocMore(size * sizeof(QChar), sizeof(Data)) / sizeof(QChar);
809 }
810
811 /*! \typedef QString::ConstIterator
812
813     Qt-style synonym for QString::const_iterator.
814 */
815
816 /*! \typedef QString::Iterator
817
818     Qt-style synonym for QString::iterator.
819 */
820
821 /*! \typedef QString::const_iterator
822
823     The QString::const_iterator typedef provides an STL-style const
824     iterator for QString.
825
826     \sa QString::iterator
827 */
828
829 /*! \typedef QString::iterator
830
831     The QString::iterator typedef provides an STL-style non-const
832     iterator for QString.
833
834     \sa QString::const_iterator
835 */
836
837 /*!
838     \typedef QString::const_reference
839
840     The QString::const_reference typedef provides an STL-style
841     const reference for QString.
842 */
843 /*!
844     \typedef QString::reference
845
846     The QString::const_reference typedef provides an STL-style
847     reference for QString.
848 */
849 /*!
850     \typedef QString::value_type
851
852     The QString::const_reference typedef provides an STL-style
853     value type for QString.
854 */
855
856 /*! \fn QString::iterator QString::begin()
857
858     Returns an \l{STL-style iterator} pointing to the first character in
859     the string.
860
861     \sa constBegin(), end()
862 */
863
864 /*! \fn QString::const_iterator QString::begin() const
865
866     \overload begin()
867 */
868
869 /*! \fn QString::const_iterator QString::constBegin() const
870
871     Returns a const \l{STL-style iterator} pointing to the first character
872     in the string.
873
874     \sa begin(), constEnd()
875 */
876
877 /*! \fn QString::iterator QString::end()
878
879     Returns an \l{STL-style iterator} pointing to the imaginary character
880     after the last character in the string.
881
882     \sa begin(), constEnd()
883 */
884
885 /*! \fn QString::const_iterator QString::end() const
886
887     \overload end()
888 */
889
890 /*! \fn QString::const_iterator QString::constEnd() const
891
892     Returns a const \l{STL-style iterator} pointing to the imaginary
893     item after the last item in the list.
894
895     \sa constBegin(), end()
896 */
897
898 /*!
899     \fn QString::QString()
900
901     Constructs a null string. Null strings are also empty.
902
903     \sa isEmpty()
904 */
905
906 /*! \fn QString::QString(const char *str)
907
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.
911
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.
916
917     \sa fromAscii(), fromLatin1(), fromLocal8Bit(), fromUtf8()
918 */
919
920 /*! \fn QString QString::fromStdString(const std::string &str)
921
922     Returns a copy of the \a str string. The given string is converted
923     to Unicode using the fromAscii() function.
924
925     This constructor is only available if Qt is configured with STL
926     compatibility enabled.
927
928     \sa  fromAscii(), fromLatin1(), fromLocal8Bit(), fromUtf8()
929 */
930
931 /*! \fn QString QString::fromStdWString(const std::wstring &str)
932
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
936     systems).
937
938     This method is only available if Qt is configured with STL
939     compatibility enabled.
940
941     \sa fromUtf16(), fromLatin1(), fromLocal8Bit(), fromUtf8(), fromUcs4()
942 */
943
944 /*! \fn QString QString::fromWCharArray(const wchar_t *string, int size)
945     \since 4.2
946
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.
950
951     If \a size is -1 (default), the \a string has to be 0 terminated.
952
953     \sa fromUtf16(), fromLatin1(), fromLocal8Bit(), fromUtf8(), fromUcs4(), fromStdWString()
954 */
955
956 /*! \fn std::wstring QString::toStdWString() const
957
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).
962
963     This operator is mostly useful to pass a QString to a function
964     that accepts a std::wstring object.
965
966     This operator is only available if Qt is configured with STL
967     compatibility enabled.
968
969     \sa utf16(), toAscii(), toLatin1(), toUtf8(), toLocal8Bit()
970 */
971
972 // ### replace with QCharIterator
973 int QString::toUcs4_helper(const ushort *uc, int length, uint *out)
974 {
975     int i = 0;
976     for (; i < length; ++i) {
977         uint u = uc[i];
978         if (QChar::isHighSurrogate(u) && i + 1 < length) {
979             ushort low = uc[i+1];
980             if (QChar::isLowSurrogate(low)) {
981                 ++i;
982                 u = QChar::surrogateToUcs4(u, low);
983             }
984         }
985         *out++ = u;
986     }
987     return i;
988 }
989
990 /*! \fn int QString::toWCharArray(wchar_t *array) const
991   \since 4.2
992
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).
997
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).
1001
1002   returns the actual length of the string in \a array.
1003
1004   \note This function does not append a null character to the array.
1005
1006   \sa utf16(), toUcs4(), toAscii(), toLatin1(), toUtf8(), toLocal8Bit(), toStdWString()
1007 */
1008
1009 /*! \fn QString::QString(const QString &other)
1010
1011     Constructs a copy of \a other.
1012
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}.
1017
1018     \sa operator=()
1019 */
1020
1021 /*!
1022     Constructs a string initialized with the first \a size characters
1023     of the QChar array \a unicode.
1024
1025     If \a unicode is 0, a null string is constructed.
1026
1027     If \a size is negative, \a unicode is assumed to point to a nul-terminated
1028     array and its length is determined dynamically. The terminating
1029     nul-character is not considered part of the string.
1030
1031     QString makes a deep copy of the string data. The unicode data is copied as
1032     is and the Byte Order Mark is preserved if present.
1033
1034     \sa fromRawData()
1035 */
1036 QString::QString(const QChar *unicode, int size)
1037 {
1038    if (!unicode) {
1039         d = const_cast<Data *>(&shared_null.str);
1040     } else {
1041         if (size < 0) {
1042             size = 0;
1043             while (unicode[size] != 0)
1044                 ++size;
1045         }
1046         if (!size) {
1047             d = const_cast<Data *>(&shared_empty.str);
1048         } else {
1049             d = (Data*) ::malloc(sizeof(Data)+(size+1)*sizeof(QChar));
1050             Q_CHECK_PTR(d);
1051             d->ref.initializeOwned();
1052             d->size = size;
1053             d->alloc = (uint) size;
1054             d->capacityReserved = false;
1055             d->offset = 0;
1056             memcpy(d->data(), unicode, size * sizeof(QChar));
1057             d->data()[size] = '\0';
1058         }
1059     }
1060 }
1061
1062 /*!
1063     Constructs a string of the given \a size with every character set
1064     to \a ch.
1065
1066     \sa fill()
1067 */
1068 QString::QString(int size, QChar ch)
1069 {
1070    if (size <= 0) {
1071         d = const_cast<Data *>(&shared_empty.str);
1072     } else {
1073         d = (Data*) ::malloc(sizeof(Data)+(size+1)*sizeof(QChar));
1074         Q_CHECK_PTR(d);
1075         d->ref.initializeOwned();
1076         d->size = size;
1077         d->alloc = (uint) size;
1078         d->capacityReserved = false;
1079         d->offset = 0;
1080         d->data()[size] = '\0';
1081         ushort *i = d->data() + size;
1082         ushort *b = d->data();
1083         const ushort value = ch.unicode();
1084         while (i != b)
1085            *--i = value;
1086     }
1087 }
1088
1089 /*! \fn QString::QString(int size, Qt::Initialization)
1090   \internal
1091
1092   Constructs a string of the given \a size without initializing the
1093   characters. This is only used in \c QStringBuilder::toString().
1094 */
1095 QString::QString(int size, Qt::Initialization)
1096 {
1097     d = (Data*) ::malloc(sizeof(Data)+(size+1)*sizeof(QChar));
1098     Q_CHECK_PTR(d);
1099     d->ref.initializeOwned();
1100     d->size = size;
1101     d->alloc = (uint) size;
1102     d->capacityReserved = false;
1103     d->offset = 0;
1104     d->data()[size] = '\0';
1105 }
1106
1107 /*! \fn QString::QString(const QLatin1String &str)
1108
1109     Constructs a copy of the Latin-1 string \a str.
1110
1111     \sa fromLatin1()
1112 */
1113
1114 /*!
1115     Constructs a string of size 1 containing the character \a ch.
1116 */
1117 QString::QString(QChar ch)
1118 {
1119     d = (Data *) ::malloc(sizeof(Data) + 2*sizeof(QChar));
1120     Q_CHECK_PTR(d);
1121     d->ref.initializeOwned();
1122     d->size = 1;
1123     d->alloc = 1;
1124     d->capacityReserved = false;
1125     d->offset = 0;
1126     d->data()[0] = ch.unicode();
1127     d->data()[1] = '\0';
1128 }
1129
1130 /*! \fn QString::QString(const QByteArray &ba)
1131
1132     Constructs a string initialized with the byte array \a ba. The
1133     given byte array is converted to Unicode using fromAscii(). Stops
1134     copying at the first 0 character, otherwise copies the entire byte
1135     array.
1136
1137     You can disable this constructor by defining \c
1138     QT_NO_CAST_FROM_ASCII when you compile your applications. This
1139     can be useful if you want to ensure that all user-visible strings
1140     go through QObject::tr(), for example.
1141
1142     \sa fromAscii(), fromLatin1(), fromLocal8Bit(), fromUtf8()
1143 */
1144
1145 /*! \fn QString::QString(const Null &)
1146     \internal
1147 */
1148
1149 /*! \fn QString &QString::operator=(const Null &)
1150     \internal
1151 */
1152
1153 /*!
1154   \fn QString::~QString()
1155
1156     Destroys the string.
1157 */
1158
1159
1160 /*! \fn void QString::swap(QString &other)
1161     \since 4.8
1162
1163     Swaps string \a other with this string. This operation is very fast and
1164     never fails.
1165 */
1166
1167 /*! \fn void QString::detach()
1168
1169     \internal
1170 */
1171
1172 /*! \fn bool QString::isDetached() const
1173
1174     \internal
1175 */
1176
1177 /*! \fn bool QString::isSharedWith(const QString &other) const
1178
1179     \internal
1180 */
1181
1182 // ### Qt 5: rename freeData() to avoid confusion. See task 197625.
1183 void QString::free(Data *d)
1184 {
1185     ::free(d);
1186 }
1187
1188 /*!
1189     Sets the size of the string to \a size characters.
1190
1191     If \a size is greater than the current size, the string is
1192     extended to make it \a size characters long with the extra
1193     characters added to the end. The new characters are uninitialized.
1194
1195     If \a size is less than the current size, characters are removed
1196     from the end.
1197
1198     Example:
1199
1200     \snippet doc/src/snippets/qstring/main.cpp 45
1201
1202     If you want to append a certain number of identical characters to
1203     the string, use \l operator+=() as follows rather than resize():
1204
1205     \snippet doc/src/snippets/qstring/main.cpp 46
1206
1207     If you want to expand the string so that it reaches a certain
1208     width and fill the new positions with a particular character, use
1209     the leftJustified() function:
1210
1211     If \a size is negative, it is equivalent to passing zero.
1212
1213     \snippet doc/src/snippets/qstring/main.cpp 47
1214
1215     \sa truncate(), reserve()
1216 */
1217
1218 void QString::resize(int size)
1219 {
1220     if (size < 0)
1221         size = 0;
1222
1223     if (d->offset && !d->ref.isShared() && size < d->size) {
1224         d->size = size;
1225         return;
1226     }
1227
1228     if (size == 0 && !d->capacityReserved) {
1229         Data *x = const_cast<Data *>(&shared_empty.str);
1230         if (!d->ref.deref())
1231             QString::free(d);
1232         d = x;
1233     } else {
1234         if (d->ref.isShared() || size > int(d->alloc) ||
1235             (!d->capacityReserved && size < d->size && size < int(d->alloc) >> 1))
1236             realloc(grow(size));
1237         if (int(d->alloc) >= size) {
1238             d->size = size;
1239             d->data()[size] = '\0';
1240         }
1241     }
1242 }
1243
1244 /*! \fn int QString::capacity() const
1245
1246     Returns the maximum number of characters that can be stored in
1247     the string without forcing a reallocation.
1248
1249     The sole purpose of this function is to provide a means of fine
1250     tuning QString's memory usage. In general, you will rarely ever
1251     need to call this function. If you want to know how many
1252     characters are in the string, call size().
1253
1254     \sa reserve(), squeeze()
1255 */
1256
1257 /*!
1258     \fn void QString::reserve(int size)
1259
1260     Attempts to allocate memory for at least \a size characters. If
1261     you know in advance how large the string will be, you can call
1262     this function, and if you resize the string often you are likely
1263     to get better performance. If \a size is an underestimate, the
1264     worst that will happen is that the QString will be a bit slower.
1265
1266     The sole purpose of this function is to provide a means of fine
1267     tuning QString's memory usage. In general, you will rarely ever
1268     need to call this function. If you want to change the size of the
1269     string, call resize().
1270
1271     This function is useful for code that needs to build up a long
1272     string and wants to avoid repeated reallocation. In this example,
1273     we want to add to the string until some condition is true, and
1274     we're fairly sure that size is large enough to make a call to
1275     reserve() worthwhile:
1276
1277     \snippet doc/src/snippets/qstring/main.cpp 44
1278
1279     \sa squeeze(), capacity()
1280 */
1281
1282 /*!
1283     \fn void QString::squeeze()
1284
1285     Releases any memory not required to store the character data.
1286
1287     The sole purpose of this function is to provide a means of fine
1288     tuning QString's memory usage. In general, you will rarely ever
1289     need to call this function.
1290
1291     \sa reserve(), capacity()
1292 */
1293
1294 // ### Qt 5: rename reallocData() to avoid confusion. 197625
1295 void QString::realloc(int alloc)
1296 {
1297     if (d->ref.isShared() || d->offset) {
1298         Data *x = static_cast<Data *>(::malloc(sizeof(Data) + (alloc+1) * sizeof(QChar)));
1299         Q_CHECK_PTR(x);
1300         x->ref.initializeOwned();
1301         x->size = qMin(alloc, d->size);
1302         x->alloc = (uint) alloc;
1303         x->capacityReserved = d->capacityReserved;
1304         x->offset =0;
1305         ::memcpy(x->data(), d->data(), x->size * sizeof(QChar));
1306         x->data()[x->size] = 0;
1307         if (!d->ref.deref())
1308             QString::free(d);
1309         d = x;
1310     } else {
1311         Data *p = static_cast<Data *>(::realloc(d, sizeof(Data) + (alloc+1) * sizeof(QChar)));
1312         Q_CHECK_PTR(p);
1313         d = p;
1314         d->alloc = alloc;
1315         d->offset = 0;
1316     }
1317 }
1318
1319 void QString::realloc()
1320 {
1321     realloc(d->size);
1322 }
1323
1324 void QString::expand(int i)
1325 {
1326     int sz = d->size;
1327     resize(qMax(i + 1, sz));
1328     if (d->size - 1 > sz) {
1329         ushort *n = d->data() + d->size - 1;
1330         ushort *e = d->data() + sz;
1331         while (n != e)
1332            * --n = ' ';
1333     }
1334 }
1335
1336 /*! \fn void QString::clear()
1337
1338     Clears the contents of the string and makes it empty.
1339
1340     \sa resize(), isEmpty()
1341 */
1342
1343 /*! \fn QString &QString::operator=(const QString &other)
1344
1345     Assigns \a other to this string and returns a reference to this
1346     string.
1347 */
1348
1349 QString &QString::operator=(const QString &other)
1350 {
1351     other.d->ref.ref();
1352     if (!d->ref.deref())
1353         QString::free(d);
1354     d = other.d;
1355     return *this;
1356 }
1357
1358
1359 /*! \fn QString &QString::operator=(const QLatin1String &str)
1360
1361     \overload operator=()
1362
1363     Assigns the Latin-1 string \a str to this string.
1364 */
1365
1366 /*! \fn QString &QString::operator=(const QByteArray &ba)
1367
1368     \overload operator=()
1369
1370     Assigns \a ba to this string. The byte array is converted to Unicode
1371     using the fromAscii() function. This function stops conversion at the
1372     first NUL character found, or the end of the \a ba byte array.
1373
1374     You can disable this operator by defining \c
1375     QT_NO_CAST_FROM_ASCII when you compile your applications. This
1376     can be useful if you want to ensure that all user-visible strings
1377     go through QObject::tr(), for example.
1378 */
1379
1380 /*! \fn QString &QString::operator=(const char *str)
1381
1382     \overload operator=()
1383
1384     Assigns \a str to this string. The const char pointer is converted
1385     to Unicode using the fromAscii() function.
1386
1387     You can disable this operator by defining \c
1388     QT_NO_CAST_FROM_ASCII when you compile your applications. This
1389     can be useful if you want to ensure that all user-visible strings
1390     go through QObject::tr(), for example.
1391 */
1392
1393 /*! \fn QString &QString::operator=(char ch)
1394
1395     \overload operator=()
1396
1397     Assigns character \a ch to this string. The character is converted
1398     to Unicode using the fromAscii() function.
1399
1400     You can disable this operator by defining \c
1401     QT_NO_CAST_FROM_ASCII when you compile your applications. This
1402     can be useful if you want to ensure that all user-visible strings
1403     go through QObject::tr(), for example.
1404 */
1405
1406 /*!
1407     \overload operator=()
1408
1409     Sets the string to contain the single character \a ch.
1410 */
1411 QString &QString::operator=(QChar ch)
1412 {
1413     return operator=(QString(ch));
1414 }
1415
1416 /*!
1417      \fn QString& QString::insert(int position, const QString &str)
1418
1419     Inserts the string \a str at the given index \a position and
1420     returns a reference to this string.
1421
1422     Example:
1423
1424     \snippet doc/src/snippets/qstring/main.cpp 26
1425
1426     If the given \a position is greater than size(), the array is
1427     first extended using resize().
1428
1429     \sa append(), prepend(), replace(), remove()
1430 */
1431
1432
1433 /*!
1434     \fn QString &QString::insert(int position, const QLatin1String &str)
1435     \overload insert()
1436
1437     Inserts the Latin-1 string \a str at the given index \a position.
1438 */
1439 QString &QString::insert(int i, const QLatin1String &str)
1440 {
1441     const uchar *s = (const uchar *)str.latin1();
1442     if (i < 0 || !s || !(*s))
1443         return *this;
1444
1445     int len = str.size();
1446     expand(qMax(d->size, i) + len - 1);
1447
1448     ::memmove(d->data() + i + len, d->data() + i, (d->size - i - len) * sizeof(QChar));
1449     for (int j = 0; j < len; ++j)
1450         d->data()[i + j] = s[j];
1451     return *this;
1452 }
1453
1454 /*!
1455     \fn QString& QString::insert(int position, const QChar *unicode, int size)
1456     \overload insert()
1457
1458     Inserts the first \a size characters of the QChar array \a unicode
1459     at the given index \a position in the string.
1460 */
1461 QString& QString::insert(int i, const QChar *unicode, int size)
1462 {
1463     if (i < 0 || size <= 0)
1464         return *this;
1465
1466     const ushort *s = (const ushort *)unicode;
1467     if (s >= d->data() && s < d->data() + d->alloc) {
1468         // Part of me - take a copy
1469         ushort *tmp = static_cast<ushort *>(::malloc(size * sizeof(QChar)));
1470         Q_CHECK_PTR(tmp);
1471         memcpy(tmp, s, size * sizeof(QChar));
1472         insert(i, reinterpret_cast<const QChar *>(tmp), size);
1473         ::free(tmp);
1474         return *this;
1475     }
1476
1477     expand(qMax(d->size, i) + size - 1);
1478
1479     ::memmove(d->data() + i + size, d->data() + i, (d->size - i - size) * sizeof(QChar));
1480     memcpy(d->data() + i, s, size * sizeof(QChar));
1481     return *this;
1482 }
1483
1484 /*!
1485     \fn QString& QString::insert(int position, QChar ch)
1486     \overload insert()
1487
1488     Inserts \a ch at the given index \a position in the string.
1489 */
1490
1491 QString& QString::insert(int i, QChar ch)
1492 {
1493     if (i < 0)
1494         i += d->size;
1495     if (i < 0)
1496         return *this;
1497     expand(qMax(i, d->size));
1498     ::memmove(d->data() + i + 1, d->data() + i, (d->size - i) * sizeof(QChar));
1499     d->data()[i] = ch.unicode();
1500     return *this;
1501 }
1502
1503 /*!
1504     Appends the string \a str onto the end of this string.
1505
1506     Example:
1507
1508     \snippet doc/src/snippets/qstring/main.cpp 9
1509
1510     This is the same as using the insert() function:
1511
1512     \snippet doc/src/snippets/qstring/main.cpp 10
1513
1514     The append() function is typically very fast (\l{constant time}),
1515     because QString preallocates extra space at the end of the string
1516     data so it can grow without reallocating the entire string each
1517     time.
1518
1519     \sa operator+=(), prepend(), insert()
1520 */
1521 QString &QString::append(const QString &str)
1522 {
1523     if (str.d != &shared_null.str) {
1524         if (d == &shared_null.str) {
1525             operator=(str);
1526         } else {
1527             if (d->ref.isShared() || d->size + str.d->size > int(d->alloc))
1528                 realloc(grow(d->size + str.d->size));
1529             memcpy(d->data() + d->size, str.d->data(), str.d->size * sizeof(QChar));
1530             d->size += str.d->size;
1531             d->data()[d->size] = '\0';
1532         }
1533     }
1534     return *this;
1535 }
1536
1537 /*!
1538   \overload append()
1539
1540   Appends the Latin-1 string \a str to this string.
1541 */
1542 QString &QString::append(const QLatin1String &str)
1543 {
1544     const uchar *s = (const uchar *)str.latin1();
1545     if (s) {
1546         int len = str.size();
1547         if (d->ref.isShared() || d->size + len > int(d->alloc))
1548             realloc(grow(d->size + len));
1549         ushort *i = d->data() + d->size;
1550         while ((*i++ = *s++))
1551             ;
1552         d->size += len;
1553     }
1554     return *this;
1555 }
1556
1557 /*! \fn QString &QString::append(const QByteArray &ba)
1558
1559     \overload append()
1560
1561     Appends the byte array \a ba to this string. The given byte array
1562     is converted to Unicode using the fromAscii() function.
1563
1564     You can disable this function by defining \c QT_NO_CAST_FROM_ASCII
1565     when you compile your applications. This can be useful if you want
1566     to ensure that all user-visible strings go through QObject::tr(),
1567     for example.
1568 */
1569
1570 /*! \fn QString &QString::append(const char *str)
1571
1572     \overload append()
1573
1574     Appends the string \a str to this string. The given const char
1575     pointer is converted to Unicode using the fromAscii() function.
1576
1577     You can disable this function by defining \c QT_NO_CAST_FROM_ASCII
1578     when you compile your applications. This can be useful if you want
1579     to ensure that all user-visible strings go through QObject::tr(),
1580     for example.
1581 */
1582
1583 /*!
1584     \overload append()
1585
1586     Appends the character \a ch to this string.
1587 */
1588 QString &QString::append(QChar ch)
1589 {
1590     if (d->ref.isShared() || d->size + 1 > int(d->alloc))
1591         realloc(grow(d->size + 1));
1592     d->data()[d->size++] = ch.unicode();
1593     d->data()[d->size] = '\0';
1594     return *this;
1595 }
1596
1597 /*! \fn QString &QString::prepend(const QString &str)
1598
1599     Prepends the string \a str to the beginning of this string and
1600     returns a reference to this string.
1601
1602     Example:
1603
1604     \snippet doc/src/snippets/qstring/main.cpp 36
1605
1606     \sa append(), insert()
1607 */
1608
1609 /*! \fn QString &QString::prepend(const QLatin1String &str)
1610
1611     \overload prepend()
1612
1613     Prepends the Latin-1 string \a str to this string.
1614 */
1615
1616 /*! \fn QString &QString::prepend(const QByteArray &ba)
1617
1618     \overload prepend()
1619
1620     Prepends the byte array \a ba to this string. The byte array is
1621     converted to Unicode using the fromAscii() function.
1622
1623     You can disable this function by defining \c
1624     QT_NO_CAST_FROM_ASCII when you compile your applications. This
1625     can be useful if you want to ensure that all user-visible strings
1626     go through QObject::tr(), for example.
1627 */
1628
1629 /*! \fn QString &QString::prepend(const char *str)
1630
1631     \overload prepend()
1632
1633     Prepends the string \a str to this string. The const char pointer
1634     is converted to Unicode using the fromAscii() function.
1635
1636     You can disable this function by defining \c
1637     QT_NO_CAST_FROM_ASCII when you compile your applications. This
1638     can be useful if you want to ensure that all user-visible strings
1639     go through QObject::tr(), for example.
1640 */
1641
1642 /*! \fn QString &QString::prepend(QChar ch)
1643
1644     \overload prepend()
1645
1646     Prepends the character \a ch to this string.
1647 */
1648
1649 /*!
1650   \fn QString &QString::remove(int position, int n)
1651
1652   Removes \a n characters from the string, starting at the given \a
1653   position index, and returns a reference to the string.
1654
1655   If the specified \a position index is within the string, but \a
1656   position + \a n is beyond the end of the string, the string is
1657   truncated at the specified \a position.
1658
1659   \snippet doc/src/snippets/qstring/main.cpp 37
1660
1661   \sa insert(), replace()
1662 */
1663 QString &QString::remove(int pos, int len)
1664 {
1665     if (pos < 0)  // count from end of string
1666         pos += d->size;
1667     if (pos < 0 || pos >= d->size) {
1668         // range problems
1669     } else if (len >= d->size - pos) {
1670         resize(pos); // truncate
1671     } else if (len > 0) {
1672         detach();
1673         memmove(d->data() + pos, d->data() + pos + len,
1674                 (d->size - pos - len + 1) * sizeof(ushort));
1675         d->size -= len;
1676     }
1677     return *this;
1678 }
1679
1680 /*!
1681   Removes every occurrence of the given \a str string in this
1682   string, and returns a reference to this string.
1683
1684   If \a cs is Qt::CaseSensitive (default), the search is
1685   case sensitive; otherwise the search is case insensitive.
1686
1687   This is the same as \c replace(str, "", cs).
1688
1689   \sa replace()
1690 */
1691 QString &QString::remove(const QString &str, Qt::CaseSensitivity cs)
1692 {
1693     if (str.d->size) {
1694         int i = 0;
1695         while ((i = indexOf(str, i, cs)) != -1)
1696             remove(i, str.d->size);
1697     }
1698     return *this;
1699 }
1700
1701 /*!
1702   Removes every occurrence of the character \a ch in this string, and
1703   returns a reference to this string.
1704
1705   If \a cs is Qt::CaseSensitive (default), the search is case
1706   sensitive; otherwise the search is case insensitive.
1707
1708   Example:
1709
1710   \snippet doc/src/snippets/qstring/main.cpp 38
1711
1712   This is the same as \c replace(ch, "", cs).
1713
1714   \sa replace()
1715 */
1716 QString &QString::remove(QChar ch, Qt::CaseSensitivity cs)
1717 {
1718     int i = 0;
1719     ushort c = ch.unicode();
1720     if (cs == Qt::CaseSensitive) {
1721         while (i < d->size)
1722             if (d->data()[i] == ch)
1723                 remove(i, 1);
1724             else
1725                 i++;
1726     } else {
1727         c = foldCase(c);
1728         while (i < d->size)
1729             if (foldCase(d->data()[i]) == c)
1730                 remove(i, 1);
1731             else
1732                 i++;
1733     }
1734     return *this;
1735 }
1736
1737 /*!
1738   \fn QString &QString::remove(const QRegExp &rx)
1739
1740   Removes every occurrence of the regular expression \a rx in the
1741   string, and returns a reference to the string. For example:
1742
1743   \snippet doc/src/snippets/qstring/main.cpp 39
1744
1745   \sa indexOf(), lastIndexOf(), replace()
1746 */
1747
1748 /*!
1749   \fn QString &QString::replace(int position, int n, const QString &after)
1750
1751   Replaces \a n characters beginning at index \a position with
1752   the string \a after and returns a reference to this string.
1753
1754   Example:
1755
1756   \snippet doc/src/snippets/qstring/main.cpp 40
1757
1758   \sa insert(), remove()
1759 */
1760 QString &QString::replace(int pos, int len, const QString &after)
1761 {
1762     QString copy = after;
1763     return replace(pos, len, copy.constData(), copy.length());
1764 }
1765
1766 /*!
1767   \fn QString &QString::replace(int position, int n, const QChar *unicode, int size)
1768   \overload replace()
1769   Replaces \a n characters beginning at index \a position with the
1770   first \a size characters of the QChar array \a unicode and returns a
1771   reference to this string.
1772 */
1773 QString &QString::replace(int pos, int len, const QChar *unicode, int size)
1774 {
1775     if (pos < 0 || pos > d->size)
1776         return *this;
1777     if (pos + len > d->size)
1778         len = d->size - pos;
1779
1780     uint index = pos;
1781     replace_helper(&index, 1, len, unicode, size);
1782     return *this;
1783 }
1784
1785 /*!
1786   \fn QString &QString::replace(int position, int n, QChar after)
1787   \overload replace()
1788
1789   Replaces \a n characters beginning at index \a position with the
1790   character \a after and returns a reference to this string.
1791 */
1792 QString &QString::replace(int pos, int len, QChar after)
1793 {
1794     return replace(pos, len, &after, 1);
1795 }
1796
1797 /*!
1798   \overload replace()
1799   Replaces every occurrence of the string \a before with the string \a
1800   after and returns a reference to this string.
1801
1802   If \a cs is Qt::CaseSensitive (default), the search is case
1803   sensitive; otherwise the search is case insensitive.
1804
1805   Example:
1806
1807   \snippet doc/src/snippets/qstring/main.cpp 41
1808
1809   \note The replacement text is not rescanned after it is inserted.
1810
1811   Example:
1812
1813   \snippet doc/src/snippets/qstring/main.cpp 86
1814 */
1815 QString &QString::replace(const QString &before, const QString &after, Qt::CaseSensitivity cs)
1816 {
1817     return replace(before.constData(), before.size(), after.constData(), after.size(), cs);
1818 }
1819
1820 /*!
1821   \internal
1822  */
1823 void QString::replace_helper(uint *indices, int nIndices, int blen, const QChar *after, int alen)
1824 {
1825     // copy *after in case it lies inside our own d->data() area
1826     // (which we could possibly invalidate via a realloc or corrupt via memcpy operations.)
1827     QChar *afterBuffer = const_cast<QChar *>(after);
1828     if (after >= reinterpret_cast<QChar *>(d->data()) && after < reinterpret_cast<QChar *>(d->data()) + d->size) {
1829         afterBuffer = static_cast<QChar *>(::malloc(alen*sizeof(QChar)));
1830         Q_CHECK_PTR(afterBuffer);
1831         ::memcpy(afterBuffer, after, alen*sizeof(QChar));
1832     }
1833
1834     QT_TRY {
1835         if (blen == alen) {
1836             // replace in place
1837             detach();
1838             for (int i = 0; i < nIndices; ++i)
1839                 memcpy(d->data() + indices[i], afterBuffer, alen * sizeof(QChar));
1840         } else if (alen < blen) {
1841             // replace from front
1842             detach();
1843             uint to = indices[0];
1844             if (alen)
1845                 memcpy(d->data()+to, after, alen*sizeof(QChar));
1846             to += alen;
1847             uint movestart = indices[0] + blen;
1848             for (int i = 1; i < nIndices; ++i) {
1849                 int msize = indices[i] - movestart;
1850                 if (msize > 0) {
1851                     memmove(d->data() + to, d->data() + movestart, msize * sizeof(QChar));
1852                     to += msize;
1853                 }
1854                 if (alen) {
1855                     memcpy(d->data() + to, afterBuffer, alen*sizeof(QChar));
1856                     to += alen;
1857                 }
1858                 movestart = indices[i] + blen;
1859             }
1860             int msize = d->size - movestart;
1861             if (msize > 0)
1862                 memmove(d->data() + to, d->data() + movestart, msize * sizeof(QChar));
1863             resize(d->size - nIndices*(blen-alen));
1864         } else {
1865             // replace from back
1866             int adjust = nIndices*(alen-blen);
1867             int newLen = d->size + adjust;
1868             int moveend = d->size;
1869             resize(newLen);
1870
1871             while (nIndices) {
1872                 --nIndices;
1873                 int movestart = indices[nIndices] + blen;
1874                 int insertstart = indices[nIndices] + nIndices*(alen-blen);
1875                 int moveto = insertstart + alen;
1876                 memmove(d->data() + moveto, d->data() + movestart,
1877                         (moveend - movestart)*sizeof(QChar));
1878                 memcpy(d->data() + insertstart, afterBuffer, alen*sizeof(QChar));
1879                 moveend = movestart-blen;
1880             }
1881         }
1882     } QT_CATCH(const std::bad_alloc &) {
1883         if (afterBuffer != after)
1884             ::free(afterBuffer);
1885         QT_RETHROW;
1886     }
1887     if (afterBuffer != after)
1888         ::free(afterBuffer);
1889 }
1890
1891 /*!
1892   \since 4.5
1893   \overload replace()
1894
1895   Replaces each occurrence in this string of the first \a blen
1896   characters of \a before with the first \a alen characters of \a
1897   after and returns a reference to this string.
1898
1899   If \a cs is Qt::CaseSensitive (default), the search is case
1900   sensitive; otherwise the search is case insensitive.
1901 */
1902 QString &QString::replace(const QChar *before, int blen,
1903                           const QChar *after, int alen,
1904                           Qt::CaseSensitivity cs)
1905 {
1906     if (d->size == 0) {
1907         if (blen)
1908             return *this;
1909     } else {
1910         if (cs == Qt::CaseSensitive && before == after && blen == alen)
1911             return *this;
1912     }
1913     if (alen == 0 && blen == 0)
1914         return *this;
1915
1916     QStringMatcher matcher(before, blen, cs);
1917
1918     int index = 0;
1919     while (1) {
1920         uint indices[1024];
1921         uint pos = 0;
1922         while (pos < 1023) {
1923             index = matcher.indexIn(*this, index);
1924             if (index == -1)
1925                 break;
1926             indices[pos++] = index;
1927             index += blen;
1928             // avoid infinite loop
1929             if (!blen)
1930                 index++;
1931         }
1932         if (!pos)
1933             break;
1934
1935         replace_helper(indices, pos, blen, after, alen);
1936
1937         if (index == -1)
1938             break;
1939         // index has to be adjusted in case we get back into the loop above.
1940         index += pos*(alen-blen);
1941     }
1942
1943     return *this;
1944 }
1945
1946 /*!
1947   \overload replace()
1948   Replaces every occurrence of the character \a ch in the string with
1949   \a after and returns a reference to this string.
1950
1951   If \a cs is Qt::CaseSensitive (default), the search is case
1952   sensitive; otherwise the search is case insensitive.
1953 */
1954 QString& QString::replace(QChar ch, const QString &after, Qt::CaseSensitivity cs)
1955 {
1956     if (after.d->size == 0)
1957         return remove(ch, cs);
1958
1959     if (after.d->size == 1)
1960         return replace(ch, after.d->data()[0], cs);
1961
1962     if (d->size == 0)
1963         return *this;
1964
1965     ushort cc = (cs == Qt::CaseSensitive ? ch.unicode() : ch.toCaseFolded().unicode());
1966
1967     int index = 0;
1968     while (1) {
1969         uint indices[1024];
1970         uint pos = 0;
1971         if (cs == Qt::CaseSensitive) {
1972             while (pos < 1023 && index < d->size) {
1973                 if (d->data()[index] == cc)
1974                     indices[pos++] = index;
1975                 index++;
1976             }
1977         } else {
1978             while (pos < 1023 && index < d->size) {
1979                 if (QChar::toCaseFolded(d->data()[index]) == cc)
1980                     indices[pos++] = index;
1981                 index++;
1982             }
1983         }
1984         if (!pos)
1985             break;
1986
1987         replace_helper(indices, pos, 1, after.constData(), after.d->size);
1988
1989         if (index == -1)
1990             break;
1991         // index has to be adjusted in case we get back into the loop above.
1992         index += pos*(after.d->size - 1);
1993     }
1994     return *this;
1995 }
1996
1997 /*!
1998   \overload replace()
1999   Replaces every occurrence of the character \a before with the
2000   character \a after and returns a reference to this string.
2001
2002   If \a cs is Qt::CaseSensitive (default), the search is case
2003   sensitive; otherwise the search is case insensitive.
2004 */
2005 QString& QString::replace(QChar before, QChar after, Qt::CaseSensitivity cs)
2006 {
2007     ushort a = after.unicode();
2008     ushort b = before.unicode();
2009     if (d->size) {
2010         detach();
2011         ushort *i = d->data();
2012         const ushort *e = i + d->size;
2013         if (cs == Qt::CaseSensitive) {
2014             for (; i != e; ++i)
2015                 if (*i == b)
2016                     *i = a;
2017         } else {
2018             b = foldCase(b);
2019             for (; i != e; ++i)
2020                 if (foldCase(*i) == b)
2021                     *i = a;
2022         }
2023     }
2024     return *this;
2025 }
2026
2027 /*!
2028   \since 4.5
2029   \overload replace()
2030
2031   Replaces every occurrence of the string \a before with the string \a
2032   after and returns a reference to this string.
2033
2034   If \a cs is Qt::CaseSensitive (default), the search is case
2035   sensitive; otherwise the search is case insensitive.
2036
2037   \note The text is not rescanned after a replacement.
2038 */
2039 QString &QString::replace(const QLatin1String &before,
2040                           const QLatin1String &after,
2041                           Qt::CaseSensitivity cs)
2042 {
2043     int alen = after.size();
2044     QVarLengthArray<ushort> a(alen);
2045     for (int i = 0; i < alen; ++i)
2046         a[i] = (uchar)after.latin1()[i];
2047     int blen = before.size();
2048     QVarLengthArray<ushort> b(blen);
2049     for (int i = 0; i < blen; ++i)
2050         b[i] = (uchar)before.latin1()[i];
2051     return replace((const QChar *)b.data(), blen, (const QChar *)a.data(), alen, cs);
2052 }
2053
2054 /*!
2055   \since 4.5
2056   \overload replace()
2057
2058   Replaces every occurrence of the string \a before with the string \a
2059   after and returns a reference to this string.
2060
2061   If \a cs is Qt::CaseSensitive (default), the search is case
2062   sensitive; otherwise the search is case insensitive.
2063
2064   \note The text is not rescanned after a replacement.
2065 */
2066 QString &QString::replace(const QLatin1String &before,
2067                           const QString &after,
2068                           Qt::CaseSensitivity cs)
2069 {
2070     int blen = before.size();
2071     QVarLengthArray<ushort> b(blen);
2072     for (int i = 0; i < blen; ++i)
2073         b[i] = (uchar)before.latin1()[i];
2074     return replace((const QChar *)b.data(), blen, after.constData(), after.d->size, cs);
2075 }
2076
2077 /*!
2078   \since 4.5
2079   \overload replace()
2080
2081   Replaces every occurrence of the string \a before with the string \a
2082   after and returns a reference to this string.
2083
2084   If \a cs is Qt::CaseSensitive (default), the search is case
2085   sensitive; otherwise the search is case insensitive.
2086
2087   \note The text is not rescanned after a replacement.
2088 */
2089 QString &QString::replace(const QString &before,
2090                           const QLatin1String &after,
2091                           Qt::CaseSensitivity cs)
2092 {
2093     int alen = after.size();
2094     QVarLengthArray<ushort> a(alen);
2095     for (int i = 0; i < alen; ++i)
2096         a[i] = (uchar)after.latin1()[i];
2097     return replace(before.constData(), before.d->size, (const QChar *)a.data(), alen, cs);
2098 }
2099
2100 /*!
2101   \since 4.5
2102   \overload replace()
2103
2104   Replaces every occurrence of the character \a c with the string \a
2105   after and returns a reference to this string.
2106
2107   If \a cs is Qt::CaseSensitive (default), the search is case
2108   sensitive; otherwise the search is case insensitive.
2109
2110   \note The text is not rescanned after a replacement.
2111 */
2112 QString &QString::replace(QChar c, const QLatin1String &after, Qt::CaseSensitivity cs)
2113 {
2114     int alen = after.size();
2115     QVarLengthArray<ushort> a(alen);
2116     for (int i = 0; i < alen; ++i)
2117         a[i] = (uchar)after.latin1()[i];
2118     return replace(&c, 1, (const QChar *)a.data(), alen, cs);
2119 }
2120
2121
2122 /*!
2123   Returns true if string \a other is equal to this string; otherwise
2124   returns false.
2125
2126   The comparison is based exclusively on the numeric Unicode values of
2127   the characters and is very fast, but is not what a human would
2128   expect. Consider sorting user-interface strings with
2129   localeAwareCompare().
2130 */
2131 bool QString::operator==(const QString &other) const
2132 {
2133     if (d->size != other.d->size)
2134         return false;
2135
2136     return qMemEquals(d->data(), other.d->data(), d->size);
2137 }
2138
2139 /*!
2140     \overload operator==()
2141 */
2142 bool QString::operator==(const QLatin1String &other) const
2143 {
2144     if (d->size != other.size())
2145         return false;
2146
2147     if (!other.size())
2148         return isEmpty();
2149
2150     const ushort *uc = d->data();
2151     const ushort *e = uc + d->size;
2152     const uchar *c = (uchar *)other.latin1();
2153
2154     while (uc < e) {
2155         if (*uc != *c)
2156             return false;
2157         ++uc;
2158         ++c;
2159     }
2160     return true;
2161 }
2162
2163 /*! \fn bool QString::operator==(const QByteArray &other) const
2164
2165     \overload operator==()
2166
2167     The \a other byte array is converted to a QString using the
2168     fromAscii() function. This function stops conversion at the
2169     first NUL character found, or the end of the byte array.
2170
2171     You can disable this operator by defining \c
2172     QT_NO_CAST_FROM_ASCII when you compile your applications. This
2173     can be useful if you want to ensure that all user-visible strings
2174     go through QObject::tr(), for example.
2175 */
2176
2177 /*! \fn bool QString::operator==(const char *other) const
2178
2179     \overload operator==()
2180
2181     The \a other const char pointer is converted to a QString using
2182     the fromAscii() function.
2183
2184     You can disable this operator by defining \c
2185     QT_NO_CAST_FROM_ASCII when you compile your applications. This
2186     can be useful if you want to ensure that all user-visible strings
2187     go through QObject::tr(), for example.
2188 */
2189
2190 /*!
2191     Returns true if this string is lexically less than string \a
2192     other; otherwise returns false.
2193
2194     The comparison is based exclusively on the numeric Unicode values
2195     of the characters and is very fast, but is not what a human would
2196     expect. Consider sorting user-interface strings using the
2197     QString::localeAwareCompare() function.
2198 */
2199 bool QString::operator<(const QString &other) const
2200 {
2201     return ucstrcmp(constData(), length(), other.constData(), other.length()) < 0;
2202 }
2203
2204 /*!
2205     \overload operator<()
2206 */
2207 bool QString::operator<(const QLatin1String &other) const
2208 {
2209     const uchar *c = (uchar *) other.latin1();
2210     if (!c || *c == 0)
2211         return false;
2212
2213     const ushort *uc = d->data();
2214     const ushort *e = uc + qMin(d->size, other.size());
2215
2216     while (uc < e) {
2217         if (*uc != *c)
2218             break;
2219         ++uc;
2220         ++c;
2221     }
2222     return (uc == e ? d->size < other.size() : *uc < *c);
2223 }
2224
2225 /*! \fn bool QString::operator<(const QByteArray &other) const
2226
2227     \overload operator<()
2228
2229     The \a other byte array is converted to a QString using the
2230     fromAscii() function. If any NUL characters ('\0') are embedded
2231     in the byte array, they will be included in the transformation.
2232
2233     You can disable this operator by defining \c
2234     QT_NO_CAST_FROM_ASCII when you compile your applications. This
2235     can be useful if you want to ensure that all user-visible strings
2236     go through QObject::tr(), for example.
2237 */
2238
2239 /*! \fn bool QString::operator<(const char *other) const
2240
2241     \overload operator<()
2242
2243     The \a other const char pointer is converted to a QString using
2244     the fromAscii() function.
2245
2246     You can disable this operator by defining \c
2247     QT_NO_CAST_FROM_ASCII when you compile your applications. This
2248     can be useful if you want to ensure that all user-visible strings
2249     go through QObject::tr(), for example.
2250 */
2251
2252 /*! \fn bool QString::operator<=(const QString &other) const
2253
2254     Returns true if this string is lexically less than or equal to
2255     string \a other; otherwise returns false.
2256
2257     The comparison is based exclusively on the numeric Unicode values
2258     of the characters and is very fast, but is not what a human would
2259     expect. Consider sorting user-interface strings with
2260     localeAwareCompare().
2261 */
2262
2263 /*! \fn bool QString::operator<=(const QLatin1String &other) const
2264
2265     \overload operator<=()
2266 */
2267
2268 /*! \fn bool QString::operator<=(const QByteArray &other) const
2269
2270     \overload operator<=()
2271
2272     The \a other byte array is converted to a QString using the
2273     fromAscii() function. If any NUL characters ('\0') are embedded
2274     in the byte array, they will be included in the transformation.
2275
2276     You can disable this operator by defining \c
2277     QT_NO_CAST_FROM_ASCII when you compile your applications. This
2278     can be useful if you want to ensure that all user-visible strings
2279     go through QObject::tr(), for example.
2280 */
2281
2282 /*! \fn bool QString::operator<=(const char *other) const
2283
2284     \overload operator<=()
2285
2286     The \a other const char pointer is converted to a QString using
2287     the fromAscii() function.
2288
2289     You can disable this operator by defining \c
2290     QT_NO_CAST_FROM_ASCII when you compile your applications. This
2291     can be useful if you want to ensure that all user-visible strings
2292     go through QObject::tr(), for example.
2293 */
2294
2295 /*! \fn bool QString::operator>(const QString &other) const
2296
2297     Returns true if this string is lexically greater than string \a
2298     other; otherwise returns false.
2299
2300     The comparison is based exclusively on the numeric Unicode values
2301     of the characters and is very fast, but is not what a human would
2302     expect. Consider sorting user-interface strings with
2303     localeAwareCompare().
2304 */
2305
2306 /*!
2307     \overload operator>()
2308 */
2309 bool QString::operator>(const QLatin1String &other) const
2310 {
2311     const uchar *c = (uchar *) other.latin1();
2312     if (!c || *c == '\0')
2313         return !isEmpty();
2314
2315     const ushort *uc = d->data();
2316     const ushort *e = uc + qMin(d->size, other.size());
2317
2318     while (uc < e) {
2319         if (*uc != *c)
2320             break;
2321         ++uc;
2322         ++c;
2323     }
2324     return (uc == e) ? d->size > other.size() : *uc > *c;
2325 }
2326
2327 /*! \fn bool QString::operator>(const QByteArray &other) const
2328
2329     \overload operator>()
2330
2331     The \a other byte array is converted to a QString using the
2332     fromAscii() function. If any NUL characters ('\0') are embedded
2333     in the byte array, they will be included in the transformation.
2334
2335     You can disable this operator by defining \c
2336     QT_NO_CAST_FROM_ASCII when you compile your applications. This
2337     can be useful if you want to ensure that all user-visible strings
2338     go through QObject::tr(), for example.
2339 */
2340
2341 /*! \fn bool QString::operator>(const char *other) const
2342
2343     \overload operator>()
2344
2345     The \a other const char pointer is converted to a QString using
2346     the fromAscii() function.
2347
2348     You can disable this operator by defining \c QT_NO_CAST_FROM_ASCII
2349     when you compile your applications. This can be useful if you want
2350     to ensure that all user-visible strings go through QObject::tr(),
2351     for example.
2352 */
2353
2354 /*! \fn bool QString::operator>=(const QString &other) const
2355
2356     Returns true if this string is lexically greater than or equal to
2357     string \a other; otherwise returns false.
2358
2359     The comparison is based exclusively on the numeric Unicode values
2360     of the characters and is very fast, but is not what a human would
2361     expect. Consider sorting user-interface strings with
2362     localeAwareCompare().
2363 */
2364
2365 /*! \fn bool QString::operator>=(const QLatin1String &other) const
2366
2367     \overload operator>=()
2368 */
2369
2370 /*! \fn bool QString::operator>=(const QByteArray &other) const
2371
2372     \overload operator>=()
2373
2374     The \a other byte array is converted to a QString using the
2375     fromAscii() function. If any NUL characters ('\0') are embedded in
2376     the byte array, they will be included in the transformation.
2377
2378     You can disable this operator by defining \c QT_NO_CAST_FROM_ASCII
2379     when you compile your applications. This can be useful if you want
2380     to ensure that all user-visible strings go through QObject::tr(),
2381     for example.
2382 */
2383
2384 /*! \fn bool QString::operator>=(const char *other) const
2385
2386     \overload operator>=()
2387
2388     The \a other const char pointer is converted to a QString using
2389     the fromAscii() function.
2390
2391     You can disable this operator by defining \c QT_NO_CAST_FROM_ASCII
2392     when you compile your applications. This can be useful if you want
2393     to ensure that all user-visible strings go through QObject::tr(),
2394     for example.
2395 */
2396
2397 /*! \fn bool QString::operator!=(const QString &other) const
2398
2399     Returns true if this string is not equal to string \a other;
2400     otherwise returns false.
2401
2402     The comparison is based exclusively on the numeric Unicode values
2403     of the characters and is very fast, but is not what a human would
2404     expect. Consider sorting user-interface strings with
2405     localeAwareCompare().
2406 */
2407
2408 /*! \fn bool QString::operator!=(const QLatin1String &other) const
2409
2410     \overload operator!=()
2411 */
2412
2413 /*! \fn bool QString::operator!=(const QByteArray &other) const
2414
2415     \overload operator!=()
2416
2417     The \a other byte array is converted to a QString using the
2418     fromAscii() function. If any NUL characters ('\0') are embedded
2419     in the byte array, they will be included in the transformation.
2420
2421     You can disable this operator by defining \c QT_NO_CAST_FROM_ASCII
2422     when you compile your applications. This can be useful if you want
2423     to ensure that all user-visible strings go through QObject::tr(),
2424     for example.
2425 */
2426
2427 /*! \fn bool QString::operator!=(const char *other) const
2428
2429     \overload operator!=()
2430
2431     The \a other const char pointer is converted to a QString using
2432     the fromAscii() function.
2433
2434     You can disable this operator by defining \c
2435     QT_NO_CAST_FROM_ASCII when you compile your applications. This
2436     can be useful if you want to ensure that all user-visible strings
2437     go through QObject::tr(), for example.
2438 */
2439
2440 /*!
2441   Returns the index position of the first occurrence of the string \a
2442   str in this string, searching forward from index position \a
2443   from. Returns -1 if \a str is not found.
2444
2445   If \a cs is Qt::CaseSensitive (default), the search is case
2446   sensitive; otherwise the search is case insensitive.
2447
2448   Example:
2449
2450   \snippet doc/src/snippets/qstring/main.cpp 24
2451
2452   If \a from is -1, the search starts at the last character; if it is
2453   -2, at the next to last character and so on.
2454
2455   \sa lastIndexOf(), contains(), count()
2456 */
2457 int QString::indexOf(const QString &str, int from, Qt::CaseSensitivity cs) const
2458 {
2459     return qFindString(unicode(), length(), from, str.unicode(), str.length(), cs);
2460 }
2461
2462 /*!
2463   \since 4.5
2464   Returns the index position of the first occurrence of the string \a
2465   str in this string, searching forward from index position \a
2466   from. Returns -1 if \a str is not found.
2467
2468   If \a cs is Qt::CaseSensitive (default), the search is case
2469   sensitive; otherwise the search is case insensitive.
2470
2471   Example:
2472
2473   \snippet doc/src/snippets/qstring/main.cpp 24
2474
2475   If \a from is -1, the search starts at the last character; if it is
2476   -2, at the next to last character and so on.
2477
2478   \sa lastIndexOf(), contains(), count()
2479 */
2480
2481 int QString::indexOf(const QLatin1String &str, int from, Qt::CaseSensitivity cs) const
2482 {
2483     return qt_find_latin1_string(unicode(), size(), str, from, cs);
2484 }
2485
2486 int qFindString(
2487     const QChar *haystack0, int haystackLen, int from,
2488     const QChar *needle0, int needleLen, Qt::CaseSensitivity cs)
2489 {
2490     const int l = haystackLen;
2491     const int sl = needleLen;
2492     if (from < 0)
2493         from += l;
2494     if (uint(sl + from) > (uint)l)
2495         return -1;
2496     if (!sl)
2497         return from;
2498     if (!l)
2499         return -1;
2500
2501     if (sl == 1)
2502         return findChar(haystack0, haystackLen, needle0[0], from, cs);
2503
2504     /*
2505         We use the Boyer-Moore algorithm in cases where the overhead
2506         for the skip table should pay off, otherwise we use a simple
2507         hash function.
2508     */
2509     if (l > 500 && sl > 5)
2510         return qFindStringBoyerMoore(haystack0, haystackLen, from,
2511             needle0, needleLen, cs);
2512
2513     /*
2514         We use some hashing for efficiency's sake. Instead of
2515         comparing strings, we compare the hash value of str with that
2516         of a part of this QString. Only if that matches, we call
2517         ucstrncmp() or ucstrnicmp().
2518     */
2519     const ushort *needle = (const ushort *)needle0;
2520     const ushort *haystack = (const ushort *)haystack0 + from;
2521     const ushort *end = (const ushort *)haystack0 + (l-sl);
2522     const int sl_minus_1 = sl-1;
2523     int hashNeedle = 0, hashHaystack = 0, idx;
2524
2525     if (cs == Qt::CaseSensitive) {
2526         for (idx = 0; idx < sl; ++idx) {
2527             hashNeedle = ((hashNeedle<<1) + needle[idx]);
2528             hashHaystack = ((hashHaystack<<1) + haystack[idx]);
2529         }
2530         hashHaystack -= haystack[sl_minus_1];
2531
2532         while (haystack <= end) {
2533             hashHaystack += haystack[sl_minus_1];
2534             if (hashHaystack == hashNeedle
2535                  && ucstrncmp((const QChar *)needle, (const QChar *)haystack, sl) == 0)
2536                 return haystack - (const ushort *)haystack0;
2537
2538             REHASH(*haystack);
2539             ++haystack;
2540         }
2541     } else {
2542         const ushort *haystack_start = (const ushort *)haystack0;
2543         for (idx = 0; idx < sl; ++idx) {
2544             hashNeedle = (hashNeedle<<1) + foldCase(needle + idx, needle);
2545             hashHaystack = (hashHaystack<<1) + foldCase(haystack + idx, haystack_start);
2546         }
2547         hashHaystack -= foldCase(haystack + sl_minus_1, haystack_start);
2548
2549         while (haystack <= end) {
2550             hashHaystack += foldCase(haystack + sl_minus_1, haystack_start);
2551             if (hashHaystack == hashNeedle && ucstrnicmp(needle, haystack, sl) == 0)
2552                 return haystack - (const ushort *)haystack0;
2553
2554             REHASH(foldCase(haystack, haystack_start));
2555             ++haystack;
2556         }
2557     }
2558     return -1;
2559 }
2560
2561 /*!
2562     \overload indexOf()
2563
2564     Returns the index position of the first occurrence of the
2565     character \a ch in the string, searching forward from index
2566     position \a from. Returns -1 if \a ch could not be found.
2567 */
2568 int QString::indexOf(QChar ch, int from, Qt::CaseSensitivity cs) const
2569 {
2570     return findChar(unicode(), length(), ch, from, cs);
2571 }
2572
2573 /*!
2574     \since 4.8
2575
2576     \overload indexOf()
2577
2578     Returns the index position of the first occurrence of the string
2579     reference \a str in this string, searching forward from index
2580     position \a from. Returns -1 if \a str is not found.
2581
2582     If \a cs is Qt::CaseSensitive (default), the search is case
2583     sensitive; otherwise the search is case insensitive.
2584 */
2585 int QString::indexOf(const QStringRef &str, int from, Qt::CaseSensitivity cs) const
2586 {
2587     return qFindString(unicode(), length(), from, str.unicode(), str.length(), cs);
2588 }
2589
2590 static int lastIndexOfHelper(const ushort *haystack, int from, const ushort *needle, int sl, Qt::CaseSensitivity cs)
2591 {
2592     /*
2593         See indexOf() for explanations.
2594     */
2595
2596     const ushort *end = haystack;
2597     haystack += from;
2598     const int sl_minus_1 = sl-1;
2599     const ushort *n = needle+sl_minus_1;
2600     const ushort *h = haystack+sl_minus_1;
2601     int hashNeedle = 0, hashHaystack = 0, idx;
2602
2603     if (cs == Qt::CaseSensitive) {
2604         for (idx = 0; idx < sl; ++idx) {
2605             hashNeedle = ((hashNeedle<<1) + *(n-idx));
2606             hashHaystack = ((hashHaystack<<1) + *(h-idx));
2607         }
2608         hashHaystack -= *haystack;
2609
2610         while (haystack >= end) {
2611             hashHaystack += *haystack;
2612             if (hashHaystack == hashNeedle
2613                  && ucstrncmp((const QChar *)needle, (const QChar *)haystack, sl) == 0)
2614                 return haystack - end;
2615             --haystack;
2616             REHASH(haystack[sl]);
2617         }
2618     } else {
2619         for (idx = 0; idx < sl; ++idx) {
2620             hashNeedle = ((hashNeedle<<1) + foldCase(n-idx, needle));
2621             hashHaystack = ((hashHaystack<<1) + foldCase(h-idx, end));
2622         }
2623         hashHaystack -= foldCase(haystack, end);
2624
2625         while (haystack >= end) {
2626             hashHaystack += foldCase(haystack, end);
2627             if (hashHaystack == hashNeedle && ucstrnicmp(needle, haystack, sl) == 0)
2628                 return haystack - end;
2629             --haystack;
2630             REHASH(foldCase(haystack + sl, end));
2631         }
2632     }
2633     return -1;
2634 }
2635
2636 /*!
2637   Returns the index position of the last occurrence of the string \a
2638   str in this string, searching backward from index position \a
2639   from. If \a from is -1 (default), the search starts at the last
2640   character; if \a from is -2, at the next to last character and so
2641   on. Returns -1 if \a str is not found.
2642
2643   If \a cs is Qt::CaseSensitive (default), the search is case
2644   sensitive; otherwise the search is case insensitive.
2645
2646   Example:
2647
2648   \snippet doc/src/snippets/qstring/main.cpp 29
2649
2650   \sa indexOf(), contains(), count()
2651 */
2652 int QString::lastIndexOf(const QString &str, int from, Qt::CaseSensitivity cs) const
2653 {
2654     const int sl = str.d->size;
2655     if (sl == 1)
2656         return lastIndexOf(QChar(str.d->data()[0]), from, cs);
2657
2658     const int l = d->size;
2659     if (from < 0)
2660         from += l;
2661     int delta = l-sl;
2662     if (from == l && sl == 0)
2663         return from;
2664     if (from < 0 || from >= l || delta < 0)
2665         return -1;
2666     if (from > delta)
2667         from = delta;
2668
2669     return lastIndexOfHelper(d->data(), from, str.d->data(), str.d->size, cs);
2670 }
2671
2672 /*!
2673   \since 4.5
2674   \overload lastIndexOf()
2675
2676   Returns the index position of the last occurrence of the string \a
2677   str in this string, searching backward from index position \a
2678   from. If \a from is -1 (default), the search starts at the last
2679   character; if \a from is -2, at the next to last character and so
2680   on. Returns -1 if \a str is not found.
2681
2682   If \a cs is Qt::CaseSensitive (default), the search is case
2683   sensitive; otherwise the search is case insensitive.
2684
2685   Example:
2686
2687   \snippet doc/src/snippets/qstring/main.cpp 29
2688
2689   \sa indexOf(), contains(), count()
2690 */
2691 int QString::lastIndexOf(const QLatin1String &str, int from, Qt::CaseSensitivity cs) const
2692 {
2693     const int sl = str.size();
2694     if (sl == 1)
2695         return lastIndexOf(QLatin1Char(str.latin1()[0]), from, cs);
2696
2697     const int l = d->size;
2698     if (from < 0)
2699         from += l;
2700     int delta = l-sl;
2701     if (from == l && sl == 0)
2702         return from;
2703     if (from < 0 || from >= l || delta < 0)
2704         return -1;
2705     if (from > delta)
2706         from = delta;
2707
2708     QVarLengthArray<ushort> s(sl);
2709     for (int i = 0; i < sl; ++i)
2710         s[i] = str.latin1()[i];
2711
2712     return lastIndexOfHelper(d->data(), from, s.data(), sl, cs);
2713 }
2714
2715 /*!
2716   \overload lastIndexOf()
2717
2718   Returns the index position of the last occurrence of the character
2719   \a ch, searching backward from position \a from.
2720 */
2721 int QString::lastIndexOf(QChar ch, int from, Qt::CaseSensitivity cs) const
2722 {
2723     return qt_last_index_of(unicode(), size(), ch, from, cs);
2724     }
2725
2726 /*!
2727   \since 4.8
2728   \overload lastIndexOf()
2729
2730   Returns the index position of the last occurrence of the string
2731   reference \a str in this string, searching backward from index
2732   position \a from. If \a from is -1 (default), the search starts at
2733   the last character; if \a from is -2, at the next to last character
2734   and so on. Returns -1 if \a str is not found.
2735
2736   If \a cs is Qt::CaseSensitive (default), the search is case
2737   sensitive; otherwise the search is case insensitive.
2738
2739   \sa indexOf(), contains(), count()
2740 */
2741 int QString::lastIndexOf(const QStringRef &str, int from, Qt::CaseSensitivity cs) const
2742 {
2743     const int sl = str.size();
2744     if (sl == 1)
2745         return lastIndexOf(str.at(0), from, cs);
2746
2747     const int l = d->size;
2748     if (from < 0)
2749         from += l;
2750     int delta = l - sl;
2751     if (from == l && sl == 0)
2752         return from;
2753     if (from < 0 || from >= l || delta < 0)
2754     return -1;
2755     if (from > delta)
2756         from = delta;
2757
2758     return lastIndexOfHelper(d->data(), from, reinterpret_cast<const ushort*>(str.unicode()),
2759                              str.size(), cs);
2760 }
2761
2762 #ifndef QT_NO_REGEXP
2763 struct QStringCapture
2764 {
2765     int pos;
2766     int len;
2767     int no;
2768 };
2769
2770 /*!
2771   \overload replace()
2772
2773   Replaces every occurrence of the regular expression \a rx in the
2774   string with \a after. Returns a reference to the string. For
2775   example:
2776
2777   \snippet doc/src/snippets/qstring/main.cpp 42
2778
2779   For regular expressions containing \l{capturing parentheses},
2780   occurrences of \bold{\\1}, \bold{\\2}, ..., in \a after are replaced
2781   with \a{rx}.cap(1), cap(2), ...
2782
2783   \snippet doc/src/snippets/qstring/main.cpp 43
2784
2785   \sa indexOf(), lastIndexOf(), remove(), QRegExp::cap()
2786 */
2787 QString& QString::replace(const QRegExp &rx, const QString &after)
2788 {
2789     QRegExp rx2(rx);
2790
2791     if (isEmpty() && rx2.indexIn(*this) == -1)
2792         return *this;
2793
2794     realloc();
2795
2796     int index = 0;
2797     int numCaptures = rx2.captureCount();
2798     int al = after.length();
2799     QRegExp::CaretMode caretMode = QRegExp::CaretAtZero;
2800
2801     if (numCaptures > 0) {
2802         const QChar *uc = after.unicode();
2803         int numBackRefs = 0;
2804
2805         for (int i = 0; i < al - 1; i++) {
2806             if (uc[i] == QLatin1Char('\\')) {
2807                 int no = uc[i + 1].digitValue();
2808                 if (no > 0 && no <= numCaptures)
2809                     numBackRefs++;
2810             }
2811         }
2812
2813         /*
2814             This is the harder case where we have back-references.
2815         */
2816         if (numBackRefs > 0) {
2817             QVarLengthArray<QStringCapture, 16> captures(numBackRefs);
2818             int j = 0;
2819
2820             for (int i = 0; i < al - 1; i++) {
2821                 if (uc[i] == QLatin1Char('\\')) {
2822                     int no = uc[i + 1].digitValue();
2823                     if (no > 0 && no <= numCaptures) {
2824                         QStringCapture capture;
2825                         capture.pos = i;
2826                         capture.len = 2;
2827
2828                         if (i < al - 2) {
2829                             int secondDigit = uc[i + 2].digitValue();
2830                             if (secondDigit != -1 && ((no * 10) + secondDigit) <= numCaptures) {
2831                                 no = (no * 10) + secondDigit;
2832                                 ++capture.len;
2833                             }
2834                         }
2835
2836                         capture.no = no;
2837                         captures[j++] = capture;
2838                     }
2839                 }
2840             }
2841
2842             while (index <= length()) {
2843                 index = rx2.indexIn(*this, index, caretMode);
2844                 if (index == -1)
2845                     break;
2846
2847                 QString after2(after);
2848                 for (j = numBackRefs - 1; j >= 0; j--) {
2849                     const QStringCapture &capture = captures[j];
2850                     after2.replace(capture.pos, capture.len, rx2.cap(capture.no));
2851                 }
2852
2853                 replace(index, rx2.matchedLength(), after2);
2854                 index += after2.length();
2855
2856                 // avoid infinite loop on 0-length matches (e.g., QRegExp("[a-z]*"))
2857                 if (rx2.matchedLength() == 0)
2858                     ++index;
2859
2860                 caretMode = QRegExp::CaretWontMatch;
2861             }
2862             return *this;
2863         }
2864     }
2865
2866     /*
2867         This is the simple and optimized case where we don't have
2868         back-references.
2869     */
2870     while (index != -1) {
2871         struct {
2872             int pos;
2873             int length;
2874         } replacements[2048];
2875
2876         int pos = 0;
2877         int adjust = 0;
2878         while (pos < 2047) {
2879             index = rx2.indexIn(*this, index, caretMode);
2880             if (index == -1)
2881                 break;
2882             int ml = rx2.matchedLength();
2883             replacements[pos].pos = index;
2884             replacements[pos++].length = ml;
2885             index += ml;
2886             adjust += al - ml;
2887             // avoid infinite loop
2888             if (!ml)
2889                 index++;
2890         }
2891         if (!pos)
2892             break;
2893         replacements[pos].pos = d->size;
2894         int newlen = d->size + adjust;
2895
2896         // to continue searching at the right position after we did
2897         // the first round of replacements
2898         if (index != -1)
2899             index += adjust;
2900         QString newstring;
2901         newstring.reserve(newlen + 1);
2902         QChar *newuc = newstring.data();
2903         QChar *uc = newuc;
2904         int copystart = 0;
2905         int i = 0;
2906         while (i < pos) {
2907             int copyend = replacements[i].pos;
2908             int size = copyend - copystart;
2909             memcpy(uc, d->data() + copystart, size * sizeof(QChar));
2910             uc += size;
2911             memcpy(uc, after.d->data(), al * sizeof(QChar));
2912             uc += al;
2913             copystart = copyend + replacements[i].length;
2914             i++;
2915         }
2916         memcpy(uc, d->data() + copystart, (d->size - copystart) * sizeof(QChar));
2917         newstring.resize(newlen);
2918         *this = newstring;
2919         caretMode = QRegExp::CaretWontMatch;
2920     }
2921     return *this;
2922 }
2923 #endif
2924
2925 /*!
2926     Returns the number of (potentially overlapping) occurrences of
2927     the string \a str in this string.
2928
2929     If \a cs is Qt::CaseSensitive (default), the search is
2930     case sensitive; otherwise the search is case insensitive.
2931
2932     \sa contains(), indexOf()
2933 */
2934
2935 int QString::count(const QString &str, Qt::CaseSensitivity cs) const
2936 {
2937     return qt_string_count(unicode(), size(), str.unicode(), str.size(), cs);
2938 }
2939
2940 /*!
2941   \overload count()
2942
2943   Returns the number of occurrences of character \a ch in the string.
2944 */
2945
2946 int QString::count(QChar ch, Qt::CaseSensitivity cs) const
2947 {
2948     return qt_string_count(unicode(), size(), ch, cs);
2949     }
2950
2951 /*!
2952     \since 4.8
2953     \overload count()
2954     Returns the number of (potentially overlapping) occurrences of the
2955     string reference \a str in this string.
2956
2957     If \a cs is Qt::CaseSensitive (default), the search is
2958     case sensitive; otherwise the search is case insensitive.
2959
2960     \sa contains(), indexOf()
2961 */
2962 int QString::count(const QStringRef &str, Qt::CaseSensitivity cs) const
2963 {
2964     return qt_string_count(unicode(), size(), str.unicode(), str.size(), cs);
2965 }
2966
2967
2968 /*! \fn bool QString::contains(const QString &str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
2969
2970     Returns true if this string contains an occurrence of the string
2971     \a str; otherwise returns false.
2972
2973     If \a cs is Qt::CaseSensitive (default), the search is
2974     case sensitive; otherwise the search is case insensitive.
2975
2976     Example:
2977     \snippet doc/src/snippets/qstring/main.cpp 17
2978
2979     \sa indexOf(), count()
2980 */
2981
2982 /*! \fn bool QString::contains(QChar ch, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
2983
2984     \overload contains()
2985
2986     Returns true if this string contains an occurrence of the
2987     character \a ch; otherwise returns false.
2988 */
2989
2990 /*! \fn bool QString::contains(const QStringRef &str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
2991     \since 4.8
2992
2993     Returns true if this string contains an occurrence of the string
2994     reference \a str; otherwise returns false.
2995
2996     If \a cs is Qt::CaseSensitive (default), the search is
2997     case sensitive; otherwise the search is case insensitive.
2998
2999     \sa indexOf(), count()
3000 */
3001
3002 /*! \fn bool QString::contains(const QRegExp &rx) const
3003
3004     \overload contains()
3005
3006     Returns true if the regular expression \a rx matches somewhere in
3007     this string; otherwise returns false.
3008 */
3009
3010 /*! \fn bool QString::contains(QRegExp &rx) const
3011     \overload contains()
3012     \since 4.5
3013
3014     Returns true if the regular expression \a rx matches somewhere in
3015     this string; otherwise returns false.
3016
3017     If there is a match, the \a rx regular expression will contain the
3018     matched captures (see QRegExp::matchedLength, QRegExp::cap).
3019 */
3020
3021 #ifndef QT_NO_REGEXP
3022 /*!
3023     \overload indexOf()
3024
3025     Returns the index position of the first match of the regular
3026     expression \a rx in the string, searching forward from index
3027     position \a from. Returns -1 if \a rx didn't match anywhere.
3028
3029     Example:
3030
3031     \snippet doc/src/snippets/qstring/main.cpp 25
3032 */
3033 int QString::indexOf(const QRegExp& rx, int from) const
3034 {
3035     QRegExp rx2(rx);
3036     return rx2.indexIn(*this, from);
3037 }
3038
3039 /*!
3040     \overload indexOf()
3041     \since 4.5
3042
3043     Returns the index position of the first match of the regular
3044     expression \a rx in the string, searching forward from index
3045     position \a from. Returns -1 if \a rx didn't match anywhere.
3046
3047     If there is a match, the \a rx regular expression will contain the
3048     matched captures (see QRegExp::matchedLength, QRegExp::cap).
3049
3050     Example:
3051
3052     \snippet doc/src/snippets/qstring/main.cpp 25
3053 */
3054 int QString::indexOf(QRegExp& rx, int from) const
3055 {
3056     return rx.indexIn(*this, from);
3057 }
3058
3059 /*!
3060     \overload lastIndexOf()
3061
3062     Returns the index position of the last match of the regular
3063     expression \a rx in the string, searching backward from index
3064     position \a from. Returns -1 if \a rx didn't match anywhere.
3065
3066     Example:
3067
3068     \snippet doc/src/snippets/qstring/main.cpp 30
3069 */
3070 int QString::lastIndexOf(const QRegExp& rx, int from) const
3071 {
3072     QRegExp rx2(rx);
3073     return rx2.lastIndexIn(*this, from);
3074 }
3075
3076 /*!
3077     \overload lastIndexOf()
3078     \since 4.5
3079
3080     Returns the index position of the last match of the regular
3081     expression \a rx in the string, searching backward from index
3082     position \a from. Returns -1 if \a rx didn't match anywhere.
3083
3084     If there is a match, the \a rx regular expression will contain the
3085     matched captures (see QRegExp::matchedLength, QRegExp::cap).
3086
3087     Example:
3088
3089     \snippet doc/src/snippets/qstring/main.cpp 30
3090 */
3091 int QString::lastIndexOf(QRegExp& rx, int from) const
3092 {
3093     return rx.lastIndexIn(*this, from);
3094 }
3095
3096 /*!
3097     \overload count()
3098
3099     Returns the number of times the regular expression \a rx matches
3100     in the string.
3101
3102     This function counts overlapping matches, so in the example
3103     below, there are four instances of "ana" or "ama":
3104
3105     \snippet doc/src/snippets/qstring/main.cpp 18
3106
3107 */
3108 int QString::count(const QRegExp& rx) const
3109 {
3110     QRegExp rx2(rx);
3111     int count = 0;
3112     int index = -1;
3113     int len = length();
3114     while (index < len - 1) {                 // count overlapping matches
3115         index = rx2.indexIn(*this, index + 1);
3116         if (index == -1)
3117             break;
3118         count++;
3119     }
3120     return count;
3121 }
3122 #endif // QT_NO_REGEXP
3123
3124 /*! \fn int QString::count() const
3125
3126     \overload count()
3127
3128     Same as size().
3129 */
3130
3131
3132 /*!
3133     \enum QString::SectionFlag
3134
3135     This enum specifies flags that can be used to affect various
3136     aspects of the section() function's behavior with respect to
3137     separators and empty fields.
3138
3139     \value SectionDefault Empty fields are counted, leading and
3140     trailing separators are not included, and the separator is
3141     compared case sensitively.
3142
3143     \value SectionSkipEmpty Treat empty fields as if they don't exist,
3144     i.e. they are not considered as far as \e start and \e end are
3145     concerned.
3146
3147     \value SectionIncludeLeadingSep Include the leading separator (if
3148     any) in the result string.
3149
3150     \value SectionIncludeTrailingSep Include the trailing separator
3151     (if any) in the result string.
3152
3153     \value SectionCaseInsensitiveSeps Compare the separator
3154     case-insensitively.
3155
3156     \sa section()
3157 */
3158
3159 /*!
3160     \fn QString QString::section(QChar sep, int start, int end = -1, SectionFlags flags) const
3161
3162     This function returns a section of the string.
3163
3164     This string is treated as a sequence of fields separated by the
3165     character, \a sep. The returned string consists of the fields from
3166     position \a start to position \a end inclusive. If \a end is not
3167     specified, all fields from position \a start to the end of the
3168     string are included. Fields are numbered 0, 1, 2, etc., counting
3169     from the left, and -1, -2, etc., counting from right to left.
3170
3171     The \a flags argument can be used to affect some aspects of the
3172     function's behavior, e.g. whether to be case sensitive, whether
3173     to skip empty fields and how to deal with leading and trailing
3174     separators; see \l{SectionFlags}.
3175
3176     \snippet doc/src/snippets/qstring/main.cpp 52
3177
3178     If \a start or \a end is negative, we count fields from the right
3179     of the string, the right-most field being -1, the one from
3180     right-most field being -2, and so on.
3181
3182     \snippet doc/src/snippets/qstring/main.cpp 53
3183
3184     \sa split()
3185 */
3186
3187 /*!
3188     \overload section()
3189
3190     \snippet doc/src/snippets/qstring/main.cpp 51
3191     \snippet doc/src/snippets/qstring/main.cpp 54
3192
3193     \sa split()
3194 */
3195
3196 QString QString::section(const QString &sep, int start, int end, SectionFlags flags) const
3197 {
3198     QStringList sections = split(sep, KeepEmptyParts,
3199                                  (flags & SectionCaseInsensitiveSeps) ? Qt::CaseInsensitive : Qt::CaseSensitive);
3200     if (sections.isEmpty())
3201         return QString();
3202     if (!(flags & SectionSkipEmpty)) {
3203         if (start < 0)
3204             start += sections.count();
3205         if (end < 0)
3206             end += sections.count();
3207     } else {
3208         int skip = 0;
3209         for (int k=0; k<sections.size(); ++k) {
3210             if (sections.at(k).isEmpty())
3211                 skip++;
3212         }
3213         if (start < 0)
3214             start += sections.count() - skip;
3215         if (end < 0)
3216             end += sections.count() - skip;
3217     }
3218     int x = 0;
3219     QString ret;
3220     int first_i = start, last_i = end;
3221     for (int i = 0; x <= end && i < sections.size(); ++i) {
3222         QString section = sections.at(i);
3223         const bool empty = section.isEmpty();
3224         if (x >= start) {
3225             if(x == start)
3226                 first_i = i;
3227             if(x == end)
3228                 last_i = i;
3229             if(x > start)
3230                 ret += sep;
3231             ret += section;
3232         }
3233         if (!empty || !(flags & SectionSkipEmpty))
3234             x++;
3235     }
3236     if((flags & SectionIncludeLeadingSep) && first_i)
3237         ret.prepend(sep);
3238     if((flags & SectionIncludeTrailingSep) && last_i < sections.size()-1)
3239         ret += sep;
3240     return ret;
3241 }
3242
3243 #ifndef QT_NO_REGEXP
3244 class qt_section_chunk {
3245 public:
3246     qt_section_chunk(int l, QString s) { length = l; string = s; }
3247     int length;
3248     QString string;
3249 };
3250
3251 /*!
3252     \overload section()
3253
3254     This string is treated as a sequence of fields separated by the
3255     regular expression, \a reg.
3256
3257     \snippet doc/src/snippets/qstring/main.cpp 55
3258
3259     \warning Using this QRegExp version is much more expensive than
3260     the overloaded string and character versions.
3261
3262     \sa split() simplified()
3263 */
3264 QString QString::section(const QRegExp &reg, int start, int end, SectionFlags flags) const
3265 {
3266     const QChar *uc = unicode();
3267     if(!uc)
3268         return QString();
3269
3270     QRegExp sep(reg);
3271     sep.setCaseSensitivity((flags & SectionCaseInsensitiveSeps) ? Qt::CaseInsensitive
3272                                                                 : Qt::CaseSensitive);
3273
3274     QList<qt_section_chunk> sections;
3275     int n = length(), m = 0, last_m = 0, last_len = 0;
3276     while ((m = sep.indexIn(*this, m)) != -1) {
3277         sections.append(qt_section_chunk(last_len, QString(uc + last_m, m - last_m)));
3278         last_m = m;
3279         last_len = sep.matchedLength();
3280         m += qMax(sep.matchedLength(), 1);
3281     }
3282     sections.append(qt_section_chunk(last_len, QString(uc + last_m, n - last_m)));
3283
3284     if(start < 0)
3285         start += sections.count();
3286     if(end < 0)
3287         end += sections.count();
3288
3289     QString ret;
3290     int x = 0;
3291     int first_i = start, last_i = end;
3292     for (int i = 0; x <= end && i < sections.size(); ++i) {
3293         const qt_section_chunk &section = sections.at(i);
3294         const bool empty = (section.length == section.string.length());
3295         if (x >= start) {
3296             if(x == start)
3297                 first_i = i;
3298             if(x == end)
3299                 last_i = i;
3300             if(x != start)
3301                 ret += section.string;
3302             else
3303                 ret += section.string.mid(section.length);
3304         }
3305         if (!empty || !(flags & SectionSkipEmpty))
3306             x++;
3307     }
3308     if((flags & SectionIncludeLeadingSep) && first_i < sections.size()) {
3309         const qt_section_chunk &section = sections.at(first_i);
3310         ret.prepend(section.string.left(section.length));
3311     }
3312     if((flags & SectionIncludeTrailingSep) && last_i+1 <= sections.size()-1) {
3313         const qt_section_chunk &section = sections.at(last_i+1);
3314         ret += section.string.left(section.length);
3315     }
3316     return ret;
3317 }
3318 #endif
3319
3320 /*!
3321     Returns a substring that contains the \a n leftmost characters
3322     of the string.
3323
3324     The entire string is returned if \a n is greater than size() or
3325     less than zero.
3326
3327     \snippet doc/src/snippets/qstring/main.cpp 31
3328
3329     \sa right(), mid(), startsWith()
3330 */
3331 QString QString::left(int n)  const
3332 {
3333     if (n >= d->size || n < 0)
3334         return *this;
3335     return QString((const QChar*) d->data(), n);
3336 }
3337
3338 /*!
3339     Returns a substring that contains the \a n rightmost characters
3340     of the string.
3341
3342     The entire string is returned if \a n is greater than size() or
3343     less than zero.
3344
3345     \snippet doc/src/snippets/qstring/main.cpp 48
3346
3347     \sa left(), mid(), endsWith()
3348 */
3349 QString QString::right(int n) const
3350 {
3351     if (n >= d->size || n < 0)
3352         return *this;
3353     return QString((const QChar*) d->data() + d->size - n, n);
3354 }
3355
3356 /*!
3357     Returns a string that contains \a n characters of this string,
3358     starting at the specified \a position index.
3359
3360     Returns a null string if the \a position index exceeds the
3361     length of the string. If there are less than \a n characters
3362     available in the string starting at the given \a position, or if
3363     \a n is -1 (default), the function returns all characters that
3364     are available from the specified \a position.
3365
3366     Example:
3367
3368     \snippet doc/src/snippets/qstring/main.cpp 34
3369
3370     \sa left(), right()
3371 */
3372
3373 QString QString::mid(int position, int n) const
3374 {
3375     if (position > d->size)
3376         return QString();
3377     if (position < 0)
3378         position = 0;
3379     if (n < 0 || n > d->size - position)
3380         n = d->size - position;
3381     if (position == 0 && n == d->size)
3382         return *this;
3383     return QString((const QChar*) d->data() + position, n);
3384 }
3385
3386 /*!
3387     Returns true if the string starts with \a s; otherwise returns
3388     false.
3389
3390     If \a cs is Qt::CaseSensitive (default), the search is
3391     case sensitive; otherwise the search is case insensitive.
3392
3393     \snippet doc/src/snippets/qstring/main.cpp 65
3394
3395     \sa endsWith()
3396 */
3397 bool QString::startsWith(const QString& s, Qt::CaseSensitivity cs) const
3398 {
3399     return qt_starts_with(isNull() ? 0 : unicode(), size(),
3400                           s.isNull() ? 0 : s.unicode(), s.size(), cs);
3401 }
3402
3403 /*!
3404   \overload startsWith()
3405  */
3406 bool QString::startsWith(const QLatin1String& s, Qt::CaseSensitivity cs) const
3407 {
3408     return qt_starts_with(isNull() ? 0 : unicode(), size(), s, cs);
3409 }
3410
3411 /*!
3412   \overload startsWith()
3413
3414   Returns true if the string starts with \a c; otherwise returns
3415   false.
3416 */
3417 bool QString::startsWith(QChar c, Qt::CaseSensitivity cs) const
3418 {
3419     return d->size
3420            && (cs == Qt::CaseSensitive
3421                ? d->data()[0] == c
3422                : foldCase(d->data()[0]) == foldCase(c.unicode()));
3423 }
3424
3425 /*!
3426     \since 4.8
3427     \overload
3428     Returns true if the string starts with the string reference \a s;
3429     otherwise returns false.
3430
3431     If \a cs is Qt::CaseSensitive (default), the search is case
3432     sensitive; otherwise the search is case insensitive.
3433
3434     \sa endsWith()
3435 */
3436 bool QString::startsWith(const QStringRef &s, Qt::CaseSensitivity cs) const
3437 {
3438     return qt_starts_with(isNull() ? 0 : unicode(), size(),
3439                           s.isNull() ? 0 : s.unicode(), s.size(), cs);
3440 }
3441
3442 /*!
3443     Returns true if the string ends with \a s; otherwise returns
3444     false.
3445
3446     If \a cs is Qt::CaseSensitive (default), the search is case
3447     sensitive; otherwise the search is case insensitive.
3448
3449     \snippet doc/src/snippets/qstring/main.cpp 20
3450
3451     \sa startsWith()
3452 */
3453 bool QString::endsWith(const QString& s, Qt::CaseSensitivity cs) const
3454 {
3455     return qt_ends_with(isNull() ? 0 : unicode(), size(),
3456                         s.isNull() ? 0 : s.unicode(), s.size(), cs);
3457     }
3458
3459 /*!
3460     \since 4.8
3461     \overload endsWith()
3462     Returns true if the string ends with the string reference \a s;
3463     otherwise returns false.
3464
3465     If \a cs is Qt::CaseSensitive (default), the search is case
3466     sensitive; otherwise the search is case insensitive.
3467
3468     \sa startsWith()
3469 */
3470 bool QString::endsWith(const QStringRef &s, Qt::CaseSensitivity cs) const
3471 {
3472     return qt_ends_with(isNull() ? 0 : unicode(), size(),
3473                         s.isNull() ? 0 : s.unicode(), s.size(), cs);
3474 }
3475
3476
3477 /*!
3478     \overload endsWith()
3479 */
3480 bool QString::endsWith(const QLatin1String& s, Qt::CaseSensitivity cs) const
3481 {
3482     return qt_ends_with(isNull() ? 0 : unicode(), size(), s, cs);
3483 }
3484
3485 /*!
3486   Returns true if the string ends with \a c; otherwise returns
3487   false.
3488
3489   \overload endsWith()
3490  */
3491 bool QString::endsWith(QChar c, Qt::CaseSensitivity cs) const
3492 {
3493     return d->size
3494            && (cs == Qt::CaseSensitive
3495                ? d->data()[d->size - 1] == c
3496                : foldCase(d->data()[d->size - 1]) == foldCase(c.unicode()));
3497 }
3498
3499
3500 #if defined(QT_ALWAYS_HAVE_SSE2)
3501 static inline __m128i mergeQuestionMarks(__m128i chunk)
3502 {
3503     const __m128i questionMark = _mm_set1_epi16('?');
3504
3505 # ifdef __SSE4_2__
3506     // compare the unsigned shorts for the range 0x0100-0xFFFF
3507     // note on the use of _mm_cmpestrm:
3508     //  The MSDN documentation online (http://technet.microsoft.com/en-us/library/bb514080.aspx)
3509     //  says for range search the following:
3510     //    For each character c in a, determine whether b0 <= c <= b1 or b2 <= c <= b3
3511     //
3512     //  However, all examples on the Internet, including from Intel
3513     //  (see http://software.intel.com/en-us/articles/xml-parsing-accelerator-with-intel-streaming-simd-extensions-4-intel-sse4/)
3514     //  put the range to be searched first
3515     //
3516     //  Disassembly and instruction-level debugging with GCC and ICC show
3517     //  that they are doing the right thing. Inverting the arguments in the
3518     //  instruction does cause a bunch of test failures.
3519
3520     const int mode = _SIDD_UWORD_OPS | _SIDD_CMP_RANGES | _SIDD_UNIT_MASK;
3521     const __m128i rangeMatch = _mm_cvtsi32_si128(0xffff0100);
3522     const __m128i offLimitMask = _mm_cmpestrm(rangeMatch, 2, chunk, 8, mode);
3523
3524     // replace the non-Latin 1 characters in the chunk with question marks
3525     chunk = _mm_blendv_epi8(chunk, questionMark, offLimitMask);
3526 # else
3527     // SSE has no compare instruction for unsigned comparison.
3528     // The variables must be shiffted + 0x8000 to be compared
3529     const __m128i signedBitOffset = _mm_set1_epi16(0x8000);
3530     const __m128i thresholdMask = _mm_set1_epi16(0xff + 0x8000);
3531
3532     const __m128i signedChunk = _mm_add_epi16(chunk, signedBitOffset);
3533     const __m128i offLimitMask = _mm_cmpgt_epi16(signedChunk, thresholdMask);
3534
3535 #  ifdef __SSE4_1__
3536     // replace the non-Latin 1 characters in the chunk with question marks
3537     chunk = _mm_blendv_epi8(chunk, questionMark, offLimitMask);
3538 #  else
3539     // offLimitQuestionMark contains '?' for each 16 bits that was off-limit
3540     // the 16 bits that were correct contains zeros
3541     const __m128i offLimitQuestionMark = _mm_and_si128(offLimitMask, questionMark);
3542
3543     // correctBytes contains the bytes that were in limit
3544     // the 16 bits that were off limits contains zeros
3545     const __m128i correctBytes = _mm_andnot_si128(offLimitMask, chunk);
3546
3547     // merge offLimitQuestionMark and correctBytes to have the result
3548     chunk = _mm_or_si128(correctBytes, offLimitQuestionMark);
3549 #  endif
3550 # endif
3551     return chunk;
3552 }
3553 #endif
3554
3555 static QByteArray toLatin1_helper(const QChar *data, int length)
3556 {
3557     QByteArray ba;
3558     if (length) {
3559         ba.resize(length);
3560         const ushort *src = reinterpret_cast<const ushort *>(data);
3561         uchar *dst = (uchar*) ba.data();
3562 #if defined(QT_ALWAYS_HAVE_SSE2)
3563         if (length >= 16) {
3564             const int chunkCount = length >> 4; // divided by 16
3565
3566             for (int i = 0; i < chunkCount; ++i) {
3567                 __m128i chunk1 = _mm_loadu_si128((__m128i*)src); // load
3568                 chunk1 = mergeQuestionMarks(chunk1);
3569                 src += 8;
3570
3571                 __m128i chunk2 = _mm_loadu_si128((__m128i*)src); // load
3572                 chunk2 = mergeQuestionMarks(chunk2);
3573                 src += 8;
3574
3575                 // pack the two vector to 16 x 8bits elements
3576                 const __m128i result = _mm_packus_epi16(chunk1, chunk2);
3577
3578                 _mm_storeu_si128((__m128i*)dst, result); // store
3579                 dst += 16;
3580             }
3581             length = length % 16;
3582         }
3583 #elif defined(QT_ALWAYS_HAVE_NEON)
3584         // Refer to the documentation of the SSE2 implementation
3585         // this use eactly the same method as for SSE except:
3586         // 1) neon has unsigned comparison
3587         // 2) packing is done to 64 bits (8 x 8bits component).
3588         if (length >= 16) {
3589             const int chunkCount = length >> 3; // divided by 8
3590             const uint16x8_t questionMark = vdupq_n_u16('?'); // set
3591             const uint16x8_t thresholdMask = vdupq_n_u16(0xff); // set
3592             for (int i = 0; i < chunkCount; ++i) {
3593                 uint16x8_t chunk = vld1q_u16((uint16_t *)src); // load
3594                 src += 8;
3595
3596                 const uint16x8_t offLimitMask = vcgtq_u16(chunk, thresholdMask); // chunk > thresholdMask
3597                 const uint16x8_t offLimitQuestionMark = vandq_u16(offLimitMask, questionMark); // offLimitMask & questionMark
3598                 const uint16x8_t correctBytes = vbicq_u16(chunk, offLimitMask); // !offLimitMask & chunk
3599                 chunk = vorrq_u16(correctBytes, offLimitQuestionMark); // correctBytes | offLimitQuestionMark
3600                 const uint8x8_t result = vmovn_u16(chunk); // narrowing move->packing
3601                 vst1_u8(dst, result); // store
3602                 dst += 8;
3603             }
3604             length = length % 8;
3605         }
3606 #endif
3607         while (length--) {
3608             *dst++ = (*src>0xff) ? '?' : (uchar) *src;
3609             ++src;
3610         }
3611     }
3612     return ba;
3613 }
3614
3615 /*!
3616     Returns a Latin-1 representation of the string as a QByteArray.
3617
3618     The returned byte array is undefined if the string contains non-Latin1
3619     characters. Those characters may be suppressed or replaced with a
3620     question mark.
3621
3622     \sa fromLatin1(), toAscii(), toUtf8(), toLocal8Bit(), QTextCodec
3623 */
3624 QByteArray QString::toLatin1() const
3625 {
3626     return toLatin1_helper(unicode(), length());
3627 }
3628
3629 /*!
3630     Returns an 8-bit representation of the string as a QByteArray.
3631
3632     If a codec has been set using QTextCodec::setCodecForCStrings(),
3633     it is used to convert Unicode to 8-bit char; otherwise this
3634     function does the same as toLatin1().
3635
3636     Note that, despite the name, this function does not necessarily return an US-ASCII
3637     (ANSI X3.4-1986) string and its result may not be US-ASCII compatible.
3638
3639     \sa fromAscii(), toLatin1(), toUtf8(), toLocal8Bit(), QTextCodec
3640 */
3641 QByteArray QString::toAscii() const
3642 {
3643 #ifndef QT_NO_TEXTCODEC
3644     if (codecForCStrings)
3645         return codecForCStrings->fromUnicode(*this);
3646 #endif // QT_NO_TEXTCODEC
3647     return toLatin1();
3648 }
3649
3650 #if !defined(Q_OS_MAC) && defined(Q_OS_UNIX)
3651 static QByteArray toLocal8Bit_helper(const QChar *data, int length)
3652 {
3653 #ifndef QT_NO_TEXTCODEC
3654     if (QTextCodec::codecForLocale())
3655         return QTextCodec::codecForLocale()->fromUnicode(data, length);
3656 #endif // QT_NO_TEXTCODEC
3657     return toLatin1_helper(data, length);
3658 }
3659 #endif
3660
3661 /*!
3662     Returns the local 8-bit representation of the string as a
3663     QByteArray. The returned byte array is undefined if the string
3664     contains characters not supported by the local 8-bit encoding.
3665
3666     QTextCodec::codecForLocale() is used to perform the conversion from
3667     Unicode. If the locale encoding could not be determined, this function
3668     does the same as toLatin1().
3669
3670     If this string contains any characters that cannot be encoded in the
3671     locale, the returned byte array is undefined. Those characters may be
3672     suppressed or replaced by another.
3673
3674     \sa fromLocal8Bit(), toAscii(), toLatin1(), toUtf8(), QTextCodec
3675 */
3676 QByteArray QString::toLocal8Bit() const
3677 {
3678 #ifndef QT_NO_TEXTCODEC
3679     if (QTextCodec::codecForLocale())
3680         return QTextCodec::codecForLocale()->fromUnicode(*this);
3681 #endif // QT_NO_TEXTCODEC
3682     return toLatin1();
3683 }
3684
3685 /*!
3686     Returns a UTF-8 representation of the string as a QByteArray.
3687
3688     UTF-8 is a Unicode codec and can represent all characters in a Unicode
3689     string like QString.
3690
3691     However, in the Unicode range, there are certain codepoints that are not
3692     considered characters. The Unicode standard reserves the last two
3693     codepoints in each Unicode Plane (U+FFFE, U+FFFF, U+1FFFE, U+1FFFF,
3694     U+2FFFE, etc.), as well as 16 codepoints in the range U+FDD0..U+FDDF,
3695     inclusive, as non-characters. If any of those appear in the string, they
3696     may be discarded and will not appear in the UTF-8 representation, or they
3697     may be replaced by one or more replacement characters.
3698
3699     \sa fromUtf8(), toAscii(), toLatin1(), toLocal8Bit(), QTextCodec
3700 */
3701 QByteArray QString::toUtf8() const
3702 {
3703     if (isNull())
3704         return QByteArray();
3705
3706     return QUtf8::convertFromUnicode(constData(), length(), 0);
3707 }
3708
3709 /*!
3710     \since 4.2
3711
3712     Returns a UCS-4/UTF-32 representation of the string as a QVector<uint>.
3713
3714     UCS-4 is a Unicode codec and is lossless. All characters from this string
3715     can be encoded in UCS-4. The vector is not null terminated.
3716
3717     \sa fromUtf8(), toAscii(), toLatin1(), toLocal8Bit(), QTextCodec, fromUcs4(), toWCharArray()
3718 */
3719 QVector<uint> QString::toUcs4() const
3720 {
3721     QVector<uint> v(length());
3722     uint *a = v.data();
3723     int len = toUcs4_helper(d->data(), length(), a);
3724     v.resize(len);
3725     return v;
3726 }
3727
3728 QString::Data *QString::fromLatin1_helper(const char *str, int size)
3729 {
3730     Data *d;
3731     if (!str) {
3732         d = const_cast<Data *>(&shared_null.str);
3733     } else if (size == 0 || (!*str && size < 0)) {
3734         d = const_cast<Data *>(&shared_empty.str);
3735     } else {
3736         if (size < 0)
3737             size = qstrlen(str);
3738         d = static_cast<Data *>(::malloc(sizeof(Data) + (size+1) * sizeof(QChar)));
3739         Q_CHECK_PTR(d);
3740         d->ref.initializeOwned();
3741         d->size = size;
3742         d->alloc = (uint) size;
3743         d->capacityReserved = false;
3744         d->offset = 0;
3745         d->data()[size] = '\0';
3746         ushort *dst = d->data();
3747         /* SIMD:
3748          * Unpacking with SSE has been shown to improve performance on recent CPUs
3749          * The same method gives no improvement with NEON.
3750          */
3751 #if defined(QT_ALWAYS_HAVE_SSE2)
3752         if (size >= 16) {
3753             int chunkCount = size >> 4; // divided by 16
3754             const __m128i nullMask = _mm_set1_epi32(0);
3755             for (int i = 0; i < chunkCount; ++i) {
3756                 const __m128i chunk = _mm_loadu_si128((__m128i*)str); // load
3757                 str += 16;
3758
3759                 // unpack the first 8 bytes, padding with zeros
3760                 const __m128i firstHalf = _mm_unpacklo_epi8(chunk, nullMask);
3761                 _mm_storeu_si128((__m128i*)dst, firstHalf); // store
3762                 dst += 8;
3763
3764                 // unpack the last 8 bytes, padding with zeros
3765                 const __m128i secondHalf = _mm_unpackhi_epi8 (chunk, nullMask);
3766                 _mm_storeu_si128((__m128i*)dst, secondHalf); // store
3767                 dst += 8;
3768             }
3769             size = size % 16;
3770         }
3771 #endif
3772         while (size--)
3773             *dst++ = (uchar)*str++;
3774     }
3775     return d;
3776 }
3777
3778 QString::Data *QString::fromAscii_helper(const char *str, int size)
3779 {
3780 #ifndef QT_NO_TEXTCODEC
3781     if (codecForCStrings) {
3782         Data *d;
3783         if (!str) {
3784             d = const_cast<Data *>(&shared_null.str);
3785         } else if (size == 0 || (!*str && size < 0)) {
3786             d = const_cast<Data *>(&shared_empty.str);
3787         } else {
3788             if (size < 0)
3789                 size = qstrlen(str);
3790             QString s = codecForCStrings->toUnicode(str, size);
3791             d = s.d;
3792             d->ref.ref();
3793         }
3794         return d;
3795     }
3796 #endif
3797     return fromLatin1_helper(str, size);
3798 }
3799
3800 /*! \fn QString QString::fromLatin1(const char *str, int size)
3801     Returns a QString initialized with the first \a size characters
3802     of the Latin-1 string \a str.
3803
3804     If \a size is -1 (default), it is taken to be strlen(\a
3805     str).
3806
3807     \sa toLatin1(), fromAscii(), fromUtf8(), fromLocal8Bit()
3808 */
3809
3810
3811 /*! \fn QString QString::fromLocal8Bit(const char *str, int size)
3812     Returns a QString initialized with the first \a size characters
3813     of the 8-bit string \a str.
3814
3815     If \a size is -1 (default), it is taken to be strlen(\a
3816     str).
3817
3818     QTextCodec::codecForLocale() is used to perform the conversion.
3819
3820     \sa toLocal8Bit(), fromAscii(), fromLatin1(), fromUtf8()
3821 */
3822 QString QString::fromLocal8Bit_helper(const char *str, int size)
3823 {
3824     if (!str)
3825         return QString();
3826     if (size == 0 || (!*str && size < 0))
3827         return QString(shared_empty);
3828 #if !defined(QT_NO_TEXTCODEC)
3829     if (size < 0)
3830         size = qstrlen(str);
3831     QTextCodec *codec = QTextCodec::codecForLocale();
3832     if (codec)
3833         return codec->toUnicode(str, size);
3834 #endif // !QT_NO_TEXTCODEC
3835     return fromLatin1(str, size);
3836 }
3837
3838 /*! \fn QString QString::fromAscii(const char *, int size);
3839     Returns a QString initialized with the first \a size characters
3840     from the string \a str.
3841
3842     If \a size is -1 (default), it is taken to be strlen(\a
3843     str).
3844
3845     Note that, despite the name, this function actually uses the codec
3846     defined by QTextCodec::setCodecForCStrings() to convert \a str to
3847     Unicode. Depending on the codec, it may not accept valid US-ASCII (ANSI
3848     X3.4-1986) input. If no codec has been set, this function does the same
3849     as fromLatin1().
3850
3851     \sa toAscii(), fromLatin1(), fromUtf8(), fromLocal8Bit()
3852 */
3853
3854 /*! \fn QString QString::fromUtf8(const char *str, int size)
3855     Returns a QString initialized with the first \a size bytes
3856     of the UTF-8 string \a str.
3857
3858     If \a size is -1 (default), it is taken to be strlen(\a
3859     str).
3860
3861     UTF-8 is a Unicode codec and can represent all characters in a Unicode
3862     string like QString. However, invalid sequences are possible with UTF-8
3863     and, if any such are found, they will be replaced with one or more
3864     "replacement characters", or suppressed. These include non-Unicode
3865     sequences, non-characters, overlong sequences or surrogate codepoints
3866     encoded into UTF-8.
3867
3868     Non-characters are codepoints that the Unicode standard reserves and must
3869     not be used in text interchange. They are the last two codepoints in each
3870     Unicode Plane (U+FFFE, U+FFFF, U+1FFFE, U+1FFFF, U+2FFFE, etc.), as well
3871     as 16 codepoints in the range U+FDD0..U+FDDF, inclusive.
3872
3873     \sa toUtf8(), fromAscii(), fromLatin1(), fromLocal8Bit()
3874 */
3875 QString QString::fromUtf8_helper(const char *str, int size)
3876 {
3877     if (!str)
3878         return QString();
3879
3880     Q_ASSERT(size != -1);
3881     return QUtf8::convertToUnicode(str, size, 0);
3882 }
3883
3884 /*!
3885     Returns a QString initialized with the first \a size characters
3886     of the Unicode string \a unicode (ISO-10646-UTF-16 encoded).
3887
3888     If \a size is -1 (default), \a unicode must be terminated
3889     with a 0.
3890
3891     This function checks for a Byte Order Mark (BOM). If it is missing,
3892     host byte order is assumed.
3893
3894     This function is slow compared to the other Unicode conversions.
3895     Use QString(const QChar *, int) or QString(const QChar *) if possible.
3896
3897     QString makes a deep copy of the Unicode data.
3898
3899     \sa utf16(), setUtf16()
3900 */
3901 QString QString::fromUtf16(const ushort *unicode, int size)
3902 {
3903     if (!unicode)
3904         return QString();
3905     if (size < 0) {
3906         size = 0;
3907         while (unicode[size] != 0)
3908             ++size;
3909     }
3910     return QUtf16::convertToUnicode((const char *)unicode, size*2, 0);
3911 }
3912
3913
3914 /*!
3915     \since 4.2
3916
3917     Returns a QString initialized with the first \a size characters
3918     of the Unicode string \a unicode (ISO-10646-UCS-4 encoded).
3919
3920     If \a size is -1 (default), \a unicode must be terminated
3921     with a 0.
3922
3923     \sa toUcs4(), fromUtf16(), utf16(), setUtf16(), fromWCharArray()
3924 */
3925 QString QString::fromUcs4(const uint *unicode, int size)
3926 {
3927     if (!unicode)
3928         return QString();
3929     if (size < 0) {
3930         size = 0;
3931         while (unicode[size] != 0)
3932             ++size;
3933     }
3934     return QUtf32::convertToUnicode((const char *)unicode, size*4, 0);
3935 }
3936
3937 /*!
3938     Resizes the string to \a size characters and copies \a unicode
3939     into the string.
3940
3941     If \a unicode is 0, nothing is copied, but the string is still
3942     resized to \a size.
3943
3944     \sa unicode(), setUtf16()
3945 */
3946 QString& QString::setUnicode(const QChar *unicode, int size)
3947 {
3948      resize(size);
3949      if (unicode && size)
3950          memcpy(d->data(), unicode, size * sizeof(QChar));
3951      return *this;
3952 }
3953
3954 /*!
3955     \fn QString &QString::setUtf16(const ushort *unicode, int size)
3956
3957     Resizes the string to \a size characters and copies \a unicode
3958     into the string.
3959
3960     If \a unicode is 0, nothing is copied, but the string is still
3961     resized to \a size.
3962
3963     Note that unlike fromUtf16(), this function does not consider BOMs and
3964     possibly differing byte ordering.
3965
3966     \sa utf16(), setUnicode()
3967 */
3968
3969 /*!
3970     Returns a string that has whitespace removed from the start
3971     and the end, and that has each sequence of internal whitespace
3972     replaced with a single space.
3973
3974     Whitespace means any character for which QChar::isSpace() returns
3975     true. This includes the ASCII characters '\\t', '\\n', '\\v',
3976     '\\f', '\\r', and ' '.
3977
3978     Example:
3979
3980     \snippet doc/src/snippets/qstring/main.cpp 57
3981
3982     \sa trimmed()
3983 */
3984 QString QString::simplified() const
3985 {
3986     if (d->size == 0)
3987         return *this;
3988
3989     const QChar * const start = reinterpret_cast<QChar *>(d->data());
3990     const QChar *from = start;
3991     const QChar *fromEnd = start + d->size;
3992     forever {
3993         QChar ch = *from;
3994         if (!ch.isSpace())
3995             break;
3996         if (++from == fromEnd) {
3997             // All-whitespace string
3998             return QString(shared_empty);
3999         }
4000     }
4001     // This loop needs no underflow check, as we already determined that
4002     // the string contains non-whitespace. If the string has exactly one
4003     // non-whitespace, it will be checked twice - we can live with that.
4004     while (fromEnd[-1].isSpace())
4005         fromEnd--;
4006     // The rest of the function depends on the fact that we already know
4007     // that the last character in the source is no whitespace.
4008     const QChar *copyFrom = from;
4009     int copyCount;
4010     forever {
4011         if (++from == fromEnd) {
4012             // Only leading and/or trailing whitespace, if any at all
4013             return mid(copyFrom - start, from - copyFrom);
4014         }
4015         QChar ch = *from;
4016         if (!ch.isSpace())
4017             continue;
4018         if (ch != QLatin1Char(' ')) {
4019             copyCount = from - copyFrom;
4020             break;
4021         }
4022         ch = *++from;
4023         if (ch.isSpace()) {
4024             copyCount = from - copyFrom - 1;
4025             break;
4026         }
4027     }
4028     // 'from' now points at the non-trailing whitespace which made the
4029     // string not simplified in the first place. 'copyCount' is the number
4030     // of already simplified characters - at least one, obviously -
4031     // without a trailing space.
4032     QString result((fromEnd - from) + copyCount, Qt::Uninitialized);
4033     QChar *to = reinterpret_cast<QChar *>(result.d->data());
4034     ::memcpy(to, copyFrom, copyCount * 2);
4035     to += copyCount;
4036     fromEnd--;
4037     QChar ch;
4038     forever {
4039         *to++ = QLatin1Char(' ');
4040         do {
4041             ch = *++from;
4042         } while (ch.isSpace());
4043         if (from == fromEnd)
4044             break;
4045         do {
4046             *to++ = ch;
4047             ch = *++from;
4048             if (from == fromEnd)
4049                 goto done;
4050         } while (!ch.isSpace());
4051     }
4052   done:
4053     *to++ = ch;
4054     result.truncate(to - reinterpret_cast<QChar *>(result.d->data()));
4055     return result;
4056 }
4057
4058 /*!
4059     Returns a string that has whitespace removed from the start and
4060     the end.
4061
4062     Whitespace means any character for which QChar::isSpace() returns
4063     true. This includes the ASCII characters '\\t', '\\n', '\\v',
4064     '\\f', '\\r', and ' '.
4065
4066     Example:
4067
4068     \snippet doc/src/snippets/qstring/main.cpp 82
4069
4070     Unlike simplified(), trimmed() leaves internal whitespace alone.
4071
4072     \sa simplified()
4073 */
4074 QString QString::trimmed() const
4075 {
4076     if (d->size == 0)
4077         return *this;
4078     const QChar *s = (const QChar*)d->data();
4079     if (!s->isSpace() && !s[d->size-1].isSpace())
4080         return *this;
4081     int start = 0;
4082     int end = d->size - 1;
4083     while (start<=end && s[start].isSpace())  // skip white space from start
4084         start++;
4085     if (start <= end) {                          // only white space
4086         while (end && s[end].isSpace())           // skip white space from end
4087             end--;
4088     }
4089     int l = end - start + 1;
4090     if (l <= 0) {
4091         return QString(shared_empty);
4092     }
4093     return QString(s + start, l);
4094 }
4095
4096 /*! \fn const QChar QString::at(int position) const
4097
4098     Returns the character at the given index \a position in the
4099     string.
4100
4101     The \a position must be a valid index position in the string
4102     (i.e., 0 <= \a position < size()).
4103
4104     \sa operator[]()
4105 */
4106
4107 /*!
4108     \fn QCharRef QString::operator[](int position)
4109
4110     Returns the character at the specified \a position in the string as a
4111     modifiable reference.
4112
4113     Example:
4114
4115     \snippet doc/src/snippets/qstring/main.cpp 85
4116
4117     The return value is of type QCharRef, a helper class for QString.
4118     When you get an object of type QCharRef, you can use it as if it
4119     were a QChar &. If you assign to it, the assignment will apply to
4120     the character in the QString from which you got the reference.
4121
4122     \sa at()
4123 */
4124
4125 /*!
4126     \fn const QChar QString::operator[](int position) const
4127
4128     \overload operator[]()
4129 */
4130
4131 /*! \fn QCharRef QString::operator[](uint position)
4132
4133 \overload operator[]()
4134
4135 Returns the character at the specified \a position in the string as a
4136 modifiable reference. Equivalent to \c at(position).
4137 */
4138
4139 /*! \fn const QChar QString::operator[](uint position) const
4140
4141 \overload operator[]()
4142 */
4143
4144 /*!
4145     \fn void QString::truncate(int position)
4146
4147     Truncates the string at the given \a position index.
4148
4149     If the specified \a position index is beyond the end of the
4150     string, nothing happens.
4151
4152     Example:
4153
4154     \snippet doc/src/snippets/qstring/main.cpp 83
4155
4156     If \a position is negative, it is equivalent to passing zero.
4157
4158     \sa chop(), resize(), left()
4159 */
4160
4161 void QString::truncate(int pos)
4162 {
4163     if (pos < d->size)
4164         resize(pos);
4165 }
4166
4167
4168 /*!
4169     Removes \a n characters from the end of the string.
4170
4171     If \a n is greater than size(), the result is an empty string.
4172
4173     Example:
4174     \snippet doc/src/snippets/qstring/main.cpp 15
4175
4176     If you want to remove characters from the \e beginning of the
4177     string, use remove() instead.
4178
4179     \sa truncate(), resize(), remove()
4180 */
4181 void QString::chop(int n)
4182 {
4183     if (n > 0)
4184         resize(d->size - n);
4185 }
4186
4187 /*!
4188     Sets every character in the string to character \a ch. If \a size
4189     is different from -1 (default), the string is resized to \a
4190     size beforehand.
4191
4192     Example:
4193
4194     \snippet doc/src/snippets/qstring/main.cpp 21
4195
4196     \sa resize()
4197 */
4198
4199 QString& QString::fill(QChar ch, int size)
4200 {
4201     resize(size < 0 ? d->size : size);
4202     if (d->size) {
4203         QChar *i = (QChar*)d->data() + d->size;
4204         QChar *b = (QChar*)d->data();
4205         while (i != b)
4206            *--i = ch;
4207     }
4208     return *this;
4209 }
4210
4211 /*!
4212     \fn int QString::length() const
4213
4214     Returns the number of characters in this string.  Equivalent to
4215     size().
4216
4217     \sa resize()
4218 */
4219
4220 /*!
4221     \fn int QString::size() const
4222
4223     Returns the number of characters in this string.
4224
4225     The last character in the string is at position size() - 1. In
4226     addition, QString ensures that the character at position size()
4227     is always '\\0', so that you can use the return value of data()
4228     and constData() as arguments to functions that expect
4229     '\\0'-terminated strings.
4230
4231     Example:
4232
4233     \snippet doc/src/snippets/qstring/main.cpp 58
4234
4235     \sa isEmpty(), resize()
4236 */
4237
4238 /*! \fn bool QString::isNull() const
4239
4240     Returns true if this string is null; otherwise returns false.
4241
4242     Example:
4243
4244     \snippet doc/src/snippets/qstring/main.cpp 28
4245
4246     Qt makes a distinction between null strings and empty strings for
4247     historical reasons. For most applications, what matters is
4248     whether or not a string contains any data, and this can be
4249     determined using the isEmpty() function.
4250
4251     \sa isEmpty()
4252 */
4253
4254 /*! \fn bool QString::isEmpty() const
4255
4256     Returns true if the string has no characters; otherwise returns
4257     false.
4258
4259     Example:
4260
4261     \snippet doc/src/snippets/qstring/main.cpp 27
4262
4263     \sa size()
4264 */
4265
4266 /*! \fn QString &QString::operator+=(const QString &other)
4267
4268     Appends the string \a other onto the end of this string and
4269     returns a reference to this string.
4270
4271     Example:
4272
4273     \snippet doc/src/snippets/qstring/main.cpp 84
4274
4275     This operation is typically very fast (\l{constant time}),
4276     because QString preallocates extra space at the end of the string
4277     data so it can grow without reallocating the entire string each
4278     time.
4279
4280     \sa append(), prepend()
4281 */
4282
4283 /*! \fn QString &QString::operator+=(const QLatin1String &str)
4284
4285     \overload operator+=()
4286
4287     Appends the Latin-1 string \a str to this string.
4288 */
4289
4290 /*! \fn QString &QString::operator+=(const QByteArray &ba)
4291
4292     \overload operator+=()
4293
4294     Appends the byte array \a ba to this string. The byte array is converted
4295     to Unicode using the fromAscii() function. If any NUL characters ('\0')
4296     are embedded in the \a ba byte array, they will be included in the
4297     transformation.
4298
4299     You can disable this function by defining \c
4300     QT_NO_CAST_FROM_ASCII when you compile your applications. This
4301     can be useful if you want to ensure that all user-visible strings
4302     go through QObject::tr(), for example.
4303 */
4304
4305 /*! \fn QString &QString::operator+=(const char *str)
4306
4307     \overload operator+=()
4308
4309     Appends the string \a str to this string. The const char pointer
4310     is converted to Unicode using the fromAscii() function.
4311
4312     You can disable this function by defining \c QT_NO_CAST_FROM_ASCII
4313     when you compile your applications. This can be useful if you want
4314     to ensure that all user-visible strings go through QObject::tr(),
4315     for example.
4316 */
4317
4318 /*! \fn QString &QString::operator+=(const QStringRef &str)
4319
4320     \overload operator+=()
4321
4322     Appends the string section referenced by \a str to this string.
4323 */
4324
4325 /*! \fn QString &QString::operator+=(char ch)
4326
4327     \overload operator+=()
4328
4329     Appends the character \a ch to this string. The character is
4330     converted to Unicode using the fromAscii() function.
4331
4332     You can disable this function by defining \c QT_NO_CAST_FROM_ASCII
4333     when you compile your applications. This can be useful if you want
4334     to ensure that all user-visible strings go through QObject::tr(),
4335     for example.
4336 */
4337
4338 /*! \fn QString &QString::operator+=(QChar ch)
4339
4340     \overload operator+=()
4341
4342     Appends the character \a ch to the string.
4343 */
4344
4345 /*! \fn QString &QString::operator+=(QChar::SpecialCharacter c)
4346
4347     \overload operator+=()
4348
4349     \internal
4350 */
4351
4352 /*!
4353     \fn bool operator==(const char *s1, const QString &s2)
4354
4355     \overload  operator==()
4356     \relates QString
4357
4358     Returns true if \a s1 is equal to \a s2; otherwise returns false.
4359     Note that no string is equal to \a s1 being 0.
4360
4361     Equivalent to \c {s1 != 0 && compare(s1, s2) == 0}.
4362
4363     \sa QString::compare()
4364 */
4365
4366 /*!
4367     \fn bool operator!=(const char *s1, const QString &s2)
4368     \relates QString
4369
4370     Returns true if \a s1 is not equal to \a s2; otherwise returns
4371     false.
4372
4373     For \a s1 != 0, this is equivalent to \c {compare(} \a s1, \a s2
4374     \c {) != 0}. Note that no string is equal to \a s1 being 0.
4375
4376     \sa QString::compare()
4377 */
4378
4379 /*!
4380     \fn bool operator<(const char *s1, const QString &s2)
4381     \relates QString
4382
4383     Returns true if \a s1 is lexically less than \a s2; otherwise
4384     returns false.  For \a s1 != 0, this is equivalent to \c
4385     {compare(s1, s2) < 0}.
4386
4387     The comparison is based exclusively on the numeric Unicode values
4388     of the characters and is very fast, but is not what a human would
4389     expect. Consider sorting user-interface strings using the
4390     QString::localeAwareCompare() function.
4391
4392     \sa QString::compare()
4393 */
4394
4395 /*!
4396     \fn bool operator<=(const char *s1, const QString &s2)
4397     \relates QString
4398
4399     Returns true if \a s1 is lexically less than or equal to \a s2;
4400     otherwise returns false.  For \a s1 != 0, this is equivalent to \c
4401     {compare(s1, s2) <= 0}.
4402
4403     The comparison is based exclusively on the numeric Unicode values
4404     of the characters and is very fast, but is not what a human would
4405     expect. Consider sorting user-interface strings with
4406     QString::localeAwareCompare().
4407
4408     \sa QString::compare()
4409 */
4410
4411 /*!
4412     \fn bool operator>(const char *s1, const QString &s2)
4413     \relates QString
4414
4415     Returns true if \a s1 is lexically greater than \a s2; otherwise
4416     returns false.  Equivalent to \c {compare(s1, s2) > 0}.
4417
4418     The comparison is based exclusively on the numeric Unicode values
4419     of the characters and is very fast, but is not what a human would
4420     expect. Consider sorting user-interface strings using the
4421     QString::localeAwareCompare() function.
4422
4423     \sa QString::compare()
4424 */
4425
4426 /*!
4427     \fn bool operator>=(const char *s1, const QString &s2)
4428     \relates QString
4429
4430     Returns true if \a s1 is lexically greater than or equal to \a s2;
4431     otherwise returns false.  For \a s1 != 0, this is equivalent to \c
4432     {compare(s1, s2) >= 0}.
4433
4434     The comparison is based exclusively on the numeric Unicode values
4435     of the characters and is very fast, but is not what a human would
4436     expect. Consider sorting user-interface strings using the
4437     QString::localeAwareCompare() function.
4438 */
4439
4440 /*!
4441     \fn const QString operator+(const QString &s1, const QString &s2)
4442     \relates QString
4443
4444     Returns a string which is the result of concatenating \a s1 and \a
4445     s2.
4446 */
4447
4448 /*!
4449     \fn const QString operator+(const QString &s1, const char *s2)
4450     \relates QString
4451
4452     Returns a string which is the result of concatenating \a s1 and \a
4453     s2 (\a s2 is converted to Unicode using the QString::fromAscii()
4454     function).
4455
4456     \sa QString::fromAscii()
4457 */
4458
4459 /*!
4460     \fn const QString operator+(const char *s1, const QString &s2)
4461     \relates QString
4462
4463     Returns a string which is the result of concatenating \a s1 and \a
4464     s2 (\a s1 is converted to Unicode using the QString::fromAscii()
4465     function).
4466
4467     \sa QString::fromAscii()
4468 */
4469
4470 /*!
4471     \fn const QString operator+(const QString &s, char ch)
4472     \relates QString
4473
4474     Returns a string which is the result of concatenating the string
4475     \a s and the character \a ch.
4476 */
4477
4478 /*!
4479     \fn const QString operator+(char ch, const QString &s)
4480     \relates QString
4481
4482     Returns a string which is the result of concatenating the
4483     character \a ch and the string \a s.
4484 */
4485
4486 /*!
4487     \fn int QString::compare(const QString &s1, const QString &s2, Qt::CaseSensitivity cs)
4488     \since 4.2
4489
4490     Compares \a s1 with \a s2 and returns an integer less than, equal
4491     to, or greater than zero if \a s1 is less than, equal to, or
4492     greater than \a s2.
4493
4494     If \a cs is Qt::CaseSensitive, the comparison is case sensitive;
4495     otherwise the comparison is case insensitive.
4496
4497     Case sensitive comparison is based exclusively on the numeric
4498     Unicode values of the characters and is very fast, but is not what
4499     a human would expect.  Consider sorting user-visible strings with
4500     localeAwareCompare().
4501
4502     \snippet doc/src/snippets/qstring/main.cpp 16
4503
4504     \sa operator==(), operator<(), operator>()
4505 */
4506
4507 /*!
4508     \fn int QString::compare(const QString &s1, const QLatin1String &s2, Qt::CaseSensitivity cs)
4509     \since 4.2
4510     \overload compare()
4511
4512     Performs a comparison of \a s1 and \a s2, using the case
4513     sensitivity setting \a cs.
4514 */
4515
4516 /*!
4517     \fn int QString::compare(const QLatin1String &s1, const QString &s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
4518
4519     \since 4.2
4520     \overload compare()
4521
4522     Performs a comparison of \a s1 and \a s2, using the case
4523     sensitivity setting \a cs.
4524 */
4525
4526
4527 /*!
4528     \overload compare()
4529     \since 4.2
4530
4531     Lexically compares this string with the \a other string and
4532     returns an integer less than, equal to, or greater than zero if
4533     this string is less than, equal to, or greater than the other
4534     string.
4535
4536     Same as compare(*this, \a other, \a cs).
4537 */
4538 int QString::compare(const QString &other, Qt::CaseSensitivity cs) const
4539 {
4540     if (cs == Qt::CaseSensitive)
4541         return ucstrcmp(constData(), length(), other.constData(), other.length());
4542     return ucstricmp(d->data(), d->data() + d->size, other.d->data(), other.d->data() + other.d->size);
4543 }
4544
4545 /*!
4546     \internal
4547     \since 4.5
4548 */
4549 int QString::compare_helper(const QChar *data1, int length1, const QChar *data2, int length2,
4550                             Qt::CaseSensitivity cs)
4551 {
4552     if (cs == Qt::CaseSensitive)
4553         return ucstrcmp(data1, length1, data2, length2);
4554     register const ushort *s1 = reinterpret_cast<const ushort *>(data1);
4555     register const ushort *s2 = reinterpret_cast<const ushort *>(data2);
4556     return ucstricmp(s1, s1 + length1, s2, s2 + length2);
4557 }
4558
4559 /*!
4560     \overload compare()
4561     \since 4.2
4562
4563     Same as compare(*this, \a other, \a cs).
4564 */
4565 int QString::compare(const QLatin1String &other, Qt::CaseSensitivity cs) const
4566 {
4567     return compare_helper(unicode(), length(), other, cs);
4568 }
4569
4570 /*!
4571   \fn int QString::compare(const QStringRef &ref, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
4572   \overload compare()
4573
4574   Compares the string reference, \a ref, with the string and returns
4575   an integer less than, equal to, or greater than zero if the string
4576   is less than, equal to, or greater than \a ref.
4577 */
4578
4579 /*!
4580   \fn int QString::compare(const QString &s1, const QStringRef &s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
4581   \overload compare()
4582 */
4583
4584 /*!
4585     \internal
4586     \since 4.5
4587 */
4588 int QString::compare_helper(const QChar *data1, int length1, QLatin1String s2,
4589                             Qt::CaseSensitivity cs)
4590 {
4591     const ushort *uc = reinterpret_cast<const ushort *>(data1);
4592     const ushort *uce = uc + length1;
4593     const uchar *c = (uchar *)s2.latin1();
4594
4595     if (!c)
4596         return length1;
4597
4598     if (cs == Qt::CaseSensitive) {
4599         const ushort *e = uc + length1;
4600         if (s2.size() < length1)
4601             e = uc + s2.size();
4602         while (uc < e) {
4603             int diff = *uc - *c;
4604             if (diff)
4605                 return diff;
4606             uc++, c++;
4607         }
4608
4609         if (uc == uce) {
4610             if (c == (const uchar *)s2.latin1() + s2.size())
4611                 return 0;
4612             return -1;
4613         }
4614         return 1;
4615     } else {
4616         return ucstricmp(uc, uce, c, c + s2.size());
4617     }
4618 }
4619
4620 /*!
4621     \fn int QString::localeAwareCompare(const QString & s1, const QString & s2)
4622
4623     Compares \a s1 with \a s2 and returns an integer less than, equal
4624     to, or greater than zero if \a s1 is less than, equal to, or
4625     greater than \a s2.
4626
4627     The comparison is performed in a locale- and also
4628     platform-dependent manner. Use this function to present sorted
4629     lists of strings to the user.
4630
4631     On Mac OS X since Qt 4.3, this function compares according the
4632     "Order for sorted lists" setting in the International prefereces panel.
4633
4634     \sa compare(), QTextCodec::locale()
4635 */
4636
4637 /*!
4638     \fn int QString::localeAwareCompare(const QStringRef &other) const
4639     \since 4.5
4640     \overload localeAwareCompare()
4641
4642     Compares this string with the \a other string and returns an
4643     integer less than, equal to, or greater than zero if this string
4644     is less than, equal to, or greater than the \a other string.
4645
4646     The comparison is performed in a locale- and also
4647     platform-dependent manner. Use this function to present sorted
4648     lists of strings to the user.
4649
4650     Same as \c {localeAwareCompare(*this, other)}.
4651 */
4652
4653 /*!
4654     \fn int QString::localeAwareCompare(const QString &s1, const QStringRef &s2)
4655     \since 4.5
4656     \overload localeAwareCompare()
4657
4658     Compares \a s1 with \a s2 and returns an integer less than, equal
4659     to, or greater than zero if \a s1 is less than, equal to, or
4660     greater than \a s2.
4661
4662     The comparison is performed in a locale- and also
4663     platform-dependent manner. Use this function to present sorted
4664     lists of strings to the user.
4665 */
4666
4667
4668 #if !defined(CSTR_LESS_THAN)
4669 #define CSTR_LESS_THAN    1
4670 #define CSTR_EQUAL        2
4671 #define CSTR_GREATER_THAN 3
4672 #endif
4673
4674 /*!
4675     \overload localeAwareCompare()
4676
4677     Compares this string with the \a other string and returns an
4678     integer less than, equal to, or greater than zero if this string
4679     is less than, equal to, or greater than the \a other string.
4680
4681     The comparison is performed in a locale- and also
4682     platform-dependent manner. Use this function to present sorted
4683     lists of strings to the user.
4684
4685     Same as \c {localeAwareCompare(*this, other)}.
4686 */
4687 int QString::localeAwareCompare(const QString &other) const
4688 {
4689     return localeAwareCompare_helper(constData(), length(), other.constData(), other.length());
4690 }
4691
4692 /*!
4693     \internal
4694     \since 4.5
4695 */
4696 int QString::localeAwareCompare_helper(const QChar *data1, int length1,
4697                                        const QChar *data2, int length2)
4698 {
4699     // do the right thing for null and empty
4700     if (length1 == 0 || length2 == 0)
4701         return ucstrcmp(data1, length1, data2, length2);
4702
4703 #if defined(Q_OS_WIN32) || defined(Q_OS_WINCE)
4704     int res = CompareString(GetUserDefaultLCID(), 0, (wchar_t*)data1, length1, (wchar_t*)data2, length2);
4705
4706     switch (res) {
4707     case CSTR_LESS_THAN:
4708         return -1;
4709     case CSTR_GREATER_THAN:
4710         return 1;
4711     default:
4712         return 0;
4713     }
4714 #elif defined (Q_OS_MAC)
4715     // Use CFStringCompare for comparing strings on Mac. This makes Qt order
4716     // strings the same way as native applications do, and also respects
4717     // the "Order for sorted lists" setting in the International preferences
4718     // panel.
4719     const CFStringRef thisString =
4720         CFStringCreateWithCharactersNoCopy(kCFAllocatorDefault,
4721             reinterpret_cast<const UniChar *>(data1), length1, kCFAllocatorNull);
4722     const CFStringRef otherString =
4723         CFStringCreateWithCharactersNoCopy(kCFAllocatorDefault,
4724             reinterpret_cast<const UniChar *>(data2), length2, kCFAllocatorNull);
4725
4726     const int result = CFStringCompare(thisString, otherString, kCFCompareLocalized);
4727     CFRelease(thisString);
4728     CFRelease(otherString);
4729     return result;
4730 #elif defined(Q_OS_UNIX)
4731 #  if defined(QT_USE_ICU)
4732     int res;
4733     if (qt_ucol_strcoll(data1, length1, data2, length2, &res)) {
4734         if (res == 0)
4735             res = ucstrcmp(data1, length1, data2, length2);
4736         return res;
4737     } // else fall through
4738 #  endif
4739     // declared in <string.h>
4740     int delta = strcoll(toLocal8Bit_helper(data1, length1), toLocal8Bit_helper(data2, length2));
4741     if (delta == 0)
4742         delta = ucstrcmp(data1, length1, data2, length2);
4743     return delta;
4744 #else
4745     return ucstrcmp(data1, length1, data2, length2);
4746 #endif
4747 }
4748
4749
4750 /*!
4751     \fn const QChar *QString::unicode() const
4752
4753     Returns a '\\0'-terminated Unicode representation of the string.
4754     The result remains valid until the string is modified.
4755
4756     \sa utf16()
4757 */
4758
4759 /*!
4760     \fn const ushort *QString::utf16() const
4761
4762     Returns the QString as a '\\0\'-terminated array of unsigned
4763     shorts. The result remains valid until the string is modified.
4764
4765     The returned string is in host byte order.
4766
4767     \sa unicode()
4768 */
4769
4770 const ushort *QString::utf16() const
4771 {
4772     if (d->offset)
4773         const_cast<QString*>(this)->realloc();   // ensure '\\0'-termination for ::fromRawData strings
4774     return d->data();
4775 }
4776
4777 /*!
4778     Returns a string of size \a width that contains this string
4779     padded by the \a fill character.
4780
4781     If \a truncate is false and the size() of the string is more than
4782     \a width, then the returned string is a copy of the string.
4783
4784     \snippet doc/src/snippets/qstring/main.cpp 32
4785
4786     If \a truncate is true and the size() of the string is more than
4787     \a width, then any characters in a copy of the string after
4788     position \a width are removed, and the copy is returned.
4789
4790     \snippet doc/src/snippets/qstring/main.cpp 33
4791
4792     \sa rightJustified()
4793 */
4794
4795 QString QString::leftJustified(int width, QChar fill, bool truncate) const
4796 {
4797     QString result;
4798     int len = length();
4799     int padlen = width - len;
4800     if (padlen > 0) {
4801         result.resize(len+padlen);
4802         if (len)
4803             memcpy(result.d->data(), d->data(), sizeof(QChar)*len);
4804         QChar *uc = (QChar*)result.d->data() + len;
4805         while (padlen--)
4806            * uc++ = fill;
4807     } else {
4808         if (truncate)
4809             result = left(width);
4810         else
4811             result = *this;
4812     }
4813     return result;
4814 }
4815
4816 /*!
4817     Returns a string of size() \a width that contains the \a fill
4818     character followed by the string. For example:
4819
4820     \snippet doc/src/snippets/qstring/main.cpp 49
4821
4822     If \a truncate is false and the size() of the string is more than
4823     \a width, then the returned string is a copy of the string.
4824
4825     If \a truncate is true and the size() of the string is more than
4826     \a width, then the resulting string is truncated at position \a
4827     width.
4828
4829     \snippet doc/src/snippets/qstring/main.cpp 50
4830
4831     \sa leftJustified()
4832 */
4833
4834 QString QString::rightJustified(int width, QChar fill, bool truncate) const
4835 {
4836     QString result;
4837     int len = length();
4838     int padlen = width - len;
4839     if (padlen > 0) {
4840         result.resize(len+padlen);
4841         QChar *uc = (QChar*)result.d->data();
4842         while (padlen--)
4843            * uc++ = fill;
4844         if (len)
4845             memcpy(uc, d->data(), sizeof(QChar)*len);
4846     } else {
4847         if (truncate)
4848             result = left(width);
4849         else
4850             result = *this;
4851     }
4852     return result;
4853 }
4854
4855 /*!
4856     Returns a lowercase copy of the string.
4857
4858     \snippet doc/src/snippets/qstring/main.cpp 75
4859
4860     The case conversion will always happen in the 'C' locale. For locale dependent
4861     case folding use QLocale::toLower()
4862
4863     \sa toUpper(), QLocale::toLower()
4864 */
4865
4866 QString QString::toLower() const
4867 {
4868     const ushort *p = d->data();
4869     if (!p)
4870         return *this;
4871     if (!d->size)
4872         return *this;
4873
4874     const ushort *e = d->data() + d->size;
4875
4876     // this avoids one out of bounds check in the loop
4877     if (QChar(*p).isLowSurrogate())
4878         ++p;
4879
4880     while (p != e) {
4881         uint c = *p;
4882         if (QChar(c).isLowSurrogate() && QChar(*(p - 1)).isHighSurrogate())
4883             c = QChar::surrogateToUcs4(*(p - 1), c);
4884         const QUnicodeTables::Properties *prop = qGetProp(c);
4885         if (prop->lowerCaseDiff || prop->lowerCaseSpecial) {
4886             QString s(d->size, Qt::Uninitialized);
4887             memcpy(s.d->data(), d->data(), (p - d->data())*sizeof(ushort));
4888             ushort *pp = s.d->data() + (p - d->data());
4889             while (p < e) {
4890                 uint c = *p;
4891                 if (QChar(c).isLowSurrogate() && QChar(*(p - 1)).isHighSurrogate())
4892                     c = QChar::surrogateToUcs4(*(p - 1), c);
4893                 prop = qGetProp(c);
4894                 if (prop->lowerCaseSpecial) {
4895                     int pos = pp - s.d->data();
4896                     s.resize(s.d->size + SPECIAL_CASE_MAX_LEN);
4897                     pp = s.d->data() + pos;
4898                     const ushort *specialCase = specialCaseMap + prop->lowerCaseDiff;
4899                     while (*specialCase)
4900                         *pp++ = *specialCase++;
4901                 } else {
4902                     *pp++ = *p + prop->lowerCaseDiff;
4903                 }
4904                 ++p;
4905             }
4906             s.truncate(pp - s.d->data());
4907             return s;
4908         }
4909         ++p;
4910     }
4911     return *this;
4912 }
4913
4914 /*!
4915     Returns the case folded equivalent of the string. For most Unicode
4916     characters this is the same as toLower().
4917 */
4918 QString QString::toCaseFolded() const
4919 {
4920     if (!d->size)
4921         return *this;
4922
4923     const ushort *p = d->data();
4924     if (!p)
4925         return *this;
4926
4927     const ushort *e = d->data() + d->size;
4928
4929     uint last = 0;
4930     while (p < e) {
4931         ushort folded = foldCase(*p, last);
4932         if (folded != *p) {
4933             QString s(*this);
4934             s.detach();
4935             ushort *pp = s.d->data() + (p - d->data());
4936             const ushort *ppe = s.d->data() + s.d->size;
4937             last = pp > s.d->data() ? *(pp - 1) : 0;
4938             while (pp < ppe) {
4939                 *pp = foldCase(*pp, last);
4940                 ++pp;
4941             }
4942             return s;
4943         }
4944         p++;
4945     }
4946     return *this;
4947 }
4948
4949 /*!
4950     Returns an uppercase copy of the string.
4951
4952     \snippet doc/src/snippets/qstring/main.cpp 81
4953
4954     The case conversion will always happen in the 'C' locale. For locale dependent
4955     case folding use QLocale::toUpper()
4956
4957     \sa toLower(), QLocale::toLower()
4958 */
4959
4960 QString QString::toUpper() const
4961 {
4962     const ushort *p = d->data();
4963     if (!p)
4964         return *this;
4965     if (!d->size)
4966         return *this;
4967
4968     const ushort *e = d->data() + d->size;
4969
4970     // this avoids one out of bounds check in the loop
4971     if (QChar(*p).isLowSurrogate())
4972         ++p;
4973
4974     while (p != e) {
4975         uint c = *p;
4976         if (QChar(c).isLowSurrogate() && QChar(*(p - 1)).isHighSurrogate())
4977             c = QChar::surrogateToUcs4(*(p - 1), c);
4978         const QUnicodeTables::Properties *prop = qGetProp(c);
4979         if (prop->upperCaseDiff || prop->upperCaseSpecial) {
4980             QString s(d->size, Qt::Uninitialized);
4981             memcpy(s.d->data(), d->data(), (p - d->data())*sizeof(ushort));
4982             ushort *pp = s.d->data() + (p - d->data());
4983             while (p < e) {
4984                 uint c = *p;
4985                 if (QChar(c).isLowSurrogate() && QChar(*(p - 1)).isHighSurrogate())
4986                     c = QChar::surrogateToUcs4(*(p - 1), c);
4987                 prop = qGetProp(c);
4988                 if (prop->upperCaseSpecial) {
4989                     int pos = pp - s.d->data();
4990                     s.resize(s.d->size + SPECIAL_CASE_MAX_LEN);
4991                     pp = s.d->data() + pos;
4992                     const ushort *specialCase = specialCaseMap + prop->upperCaseDiff;
4993                     while (*specialCase)
4994                         *pp++ = *specialCase++;
4995                 } else {
4996                     *pp++ = *p + prop->upperCaseDiff;
4997                 }
4998                 ++p;
4999             }
5000             s.truncate(pp - s.d->data());
5001             return s;
5002         }
5003         ++p;
5004     }
5005     return *this;
5006 }
5007
5008 // ### Qt 5: Consider whether this function shouldn't be removed See task 202871.
5009 /*!
5010     Safely builds a formatted string from the format string \a cformat
5011     and an arbitrary list of arguments.
5012
5013     The %lc escape sequence expects a unicode character of type ushort
5014     (as returned by QChar::unicode()). The %ls escape sequence expects
5015     a pointer to a zero-terminated array of unicode characters of type
5016     ushort (as returned by QString::utf16()).
5017
5018     \note This function expects a UTF-8 string for %s and Latin-1 for
5019     the format string.
5020
5021     The format string supports most of the conversion specifiers
5022     provided by printf() in the standard C++ library. It doesn't
5023     honor the length modifiers (e.g. \c h for \c short, \c ll for
5024     \c{long long}). If you need those, use the standard snprintf()
5025     function instead:
5026
5027     \snippet doc/src/snippets/qstring/main.cpp 63
5028
5029     \warning We do not recommend using QString::sprintf() in new Qt
5030     code. Instead, consider using QTextStream or arg(), both of
5031     which support Unicode strings seamlessly and are type-safe.
5032     Here's an example that uses QTextStream:
5033
5034     \snippet doc/src/snippets/qstring/main.cpp 64
5035
5036     For \l {QObject::tr()}{translations}, especially if the strings
5037     contains more than one escape sequence, you should consider using
5038     the arg() function instead. This allows the order of the
5039     replacements to be controlled by the translator.
5040
5041     \sa arg()
5042 */
5043
5044 QString &QString::sprintf(const char *cformat, ...)
5045 {
5046     va_list ap;
5047     va_start(ap, cformat);
5048     QString &s = vsprintf(cformat, ap);
5049     va_end(ap);
5050     return s;
5051 }
5052
5053 /*!
5054     Equivalent method to sprintf(), but takes a va_list \a ap
5055     instead a list of variable arguments. See the sprintf()
5056     documentation for an explanation of \a cformat.
5057
5058     This method does not call the va_end macro, the caller
5059     is responsible to call va_end on \a ap.
5060
5061     \sa sprintf()
5062 */
5063
5064 QString &QString::vsprintf(const char* cformat, va_list ap)
5065 {
5066     QLocale locale(QLocale::C);
5067
5068     if (!cformat || !*cformat) {
5069         // Qt 1.x compat
5070         *this = fromLatin1("");
5071         return *this;
5072     }
5073
5074     // Parse cformat
5075
5076     QString result;
5077     const char *c = cformat;
5078     for (;;) {
5079         // Copy non-escape chars to result
5080 #ifndef QT_NO_TEXTCODEC
5081         int i = 0;
5082         while (*(c + i) != '\0' && *(c + i) != '%')
5083             ++i;
5084         if (codecForCStrings)
5085             result.append(codecForCStrings->toUnicode(c, i));
5086         else
5087             result.append(fromLatin1(c, i));
5088         c += i;
5089 #else
5090         while (*c != '\0' && *c != '%')
5091             result.append(QLatin1Char(*c++));
5092 #endif
5093
5094         if (*c == '\0')
5095             break;
5096
5097         // Found '%'
5098         const char *escape_start = c;
5099         ++c;
5100
5101         if (*c == '\0') {
5102             result.append(QLatin1Char('%')); // a % at the end of the string - treat as non-escape text
5103             break;
5104         }
5105         if (*c == '%') {
5106             result.append(QLatin1Char('%')); // %%
5107             ++c;
5108             continue;
5109         }
5110
5111         // Parse flag characters
5112         uint flags = 0;
5113         bool no_more_flags = false;
5114         do {
5115             switch (*c) {
5116                 case '#': flags |= QLocalePrivate::Alternate; break;
5117                 case '0': flags |= QLocalePrivate::ZeroPadded; break;
5118                 case '-': flags |= QLocalePrivate::LeftAdjusted; break;
5119                 case ' ': flags |= QLocalePrivate::BlankBeforePositive; break;
5120                 case '+': flags |= QLocalePrivate::AlwaysShowSign; break;
5121                 case '\'': flags |= QLocalePrivate::ThousandsGroup; break;
5122                 default: no_more_flags = true; break;
5123             }
5124
5125             if (!no_more_flags)
5126                 ++c;
5127         } while (!no_more_flags);
5128
5129         if (*c == '\0') {
5130             result.append(QLatin1String(escape_start)); // incomplete escape, treat as non-escape text
5131             break;
5132         }
5133
5134         // Parse field width
5135         int width = -1; // -1 means unspecified
5136         if (qIsDigit(*c)) {
5137             QString width_str;
5138             while (*c != '\0' && qIsDigit(*c))
5139                 width_str.append(QLatin1Char(*c++));
5140
5141             // can't be negative - started with a digit
5142             // contains at least one digit
5143             width = width_str.toInt();
5144         }
5145         else if (*c == '*') {
5146             width = va_arg(ap, int);
5147             if (width < 0)
5148                 width = -1; // treat all negative numbers as unspecified
5149             ++c;
5150         }
5151
5152         if (*c == '\0') {
5153             result.append(QLatin1String(escape_start)); // incomplete escape, treat as non-escape text
5154             break;
5155         }
5156
5157         // Parse precision
5158         int precision = -1; // -1 means unspecified
5159         if (*c == '.') {
5160             ++c;
5161             if (qIsDigit(*c)) {
5162                 QString precision_str;
5163                 while (*c != '\0' && qIsDigit(*c))
5164                     precision_str.append(QLatin1Char(*c++));
5165
5166                 // can't be negative - started with a digit
5167                 // contains at least one digit
5168                 precision = precision_str.toInt();
5169             }
5170             else if (*c == '*') {
5171                 precision = va_arg(ap, int);
5172                 if (precision < 0)
5173                     precision = -1; // treat all negative numbers as unspecified
5174                 ++c;
5175             }
5176         }
5177
5178         if (*c == '\0') {
5179             result.append(QLatin1String(escape_start)); // incomplete escape, treat as non-escape text
5180             break;
5181         }
5182
5183         // Parse the length modifier
5184         enum LengthMod { lm_none, lm_hh, lm_h, lm_l, lm_ll, lm_L, lm_j, lm_z, lm_t };
5185         LengthMod length_mod = lm_none;
5186         switch (*c) {
5187             case 'h':
5188                 ++c;
5189                 if (*c == 'h') {
5190                     length_mod = lm_hh;
5191                     ++c;
5192                 }
5193                 else
5194                     length_mod = lm_h;
5195                 break;
5196
5197             case 'l':
5198                 ++c;
5199                 if (*c == 'l') {
5200                     length_mod = lm_ll;
5201                     ++c;
5202                 }
5203                 else
5204                     length_mod = lm_l;
5205                 break;
5206
5207             case 'L':
5208                 ++c;
5209                 length_mod = lm_L;
5210                 break;
5211
5212             case 'j':
5213                 ++c;
5214                 length_mod = lm_j;
5215                 break;
5216
5217             case 'z':
5218             case 'Z':
5219                 ++c;
5220                 length_mod = lm_z;
5221                 break;
5222
5223             case 't':
5224                 ++c;
5225                 length_mod = lm_t;
5226                 break;
5227
5228             default: break;
5229         }
5230
5231         if (*c == '\0') {
5232             result.append(QLatin1String(escape_start)); // incomplete escape, treat as non-escape text
5233             break;
5234         }
5235
5236         // Parse the conversion specifier and do the conversion
5237         QString subst;
5238         switch (*c) {
5239             case 'd':
5240             case 'i': {
5241                 qint64 i;
5242                 switch (length_mod) {
5243                     case lm_none: i = va_arg(ap, int); break;
5244                     case lm_hh: i = va_arg(ap, int); break;
5245                     case lm_h: i = va_arg(ap, int); break;
5246                     case lm_l: i = va_arg(ap, long int); break;
5247                     case lm_ll: i = va_arg(ap, qint64); break;
5248                     case lm_j: i = va_arg(ap, long int); break;
5249                     case lm_z: i = va_arg(ap, size_t); break;
5250                     case lm_t: i = va_arg(ap, int); break;
5251                     default: i = 0; break;
5252                 }
5253                 subst = locale.d()->longLongToString(i, precision, 10, width, flags);
5254                 ++c;
5255                 break;
5256             }
5257             case 'o':
5258             case 'u':
5259             case 'x':
5260             case 'X': {
5261                 quint64 u;
5262                 switch (length_mod) {
5263                     case lm_none: u = va_arg(ap, uint); break;
5264                     case lm_hh: u = va_arg(ap, uint); break;
5265                     case lm_h: u = va_arg(ap, uint); break;
5266                     case lm_l: u = va_arg(ap, ulong); break;
5267                     case lm_ll: u = va_arg(ap, quint64); break;
5268                     case lm_z: u = va_arg(ap, size_t); break;
5269                     default: u = 0; break;
5270                 }
5271
5272                 if (qIsUpper(*c))
5273                     flags |= QLocalePrivate::CapitalEorX;
5274
5275                 int base = 10;
5276                 switch (qToLower(*c)) {
5277                     case 'o':
5278                         base = 8; break;
5279                     case 'u':
5280                         base = 10; break;
5281                     case 'x':
5282                         base = 16; break;
5283                     default: break;
5284                 }
5285                 subst = locale.d()->unsLongLongToString(u, precision, base, width, flags);
5286                 ++c;
5287                 break;
5288             }
5289             case 'E':
5290             case 'e':
5291             case 'F':
5292             case 'f':
5293             case 'G':
5294             case 'g':
5295             case 'A':
5296             case 'a': {
5297                 double d;
5298                 if (length_mod == lm_L)
5299                     d = va_arg(ap, long double); // not supported - converted to a double
5300                 else
5301                     d = va_arg(ap, double);
5302
5303                 if (qIsUpper(*c))
5304                     flags |= QLocalePrivate::CapitalEorX;
5305
5306                 QLocalePrivate::DoubleForm form = QLocalePrivate::DFDecimal;
5307                 switch (qToLower(*c)) {
5308                     case 'e': form = QLocalePrivate::DFExponent; break;
5309                     case 'a':                             // not supported - decimal form used instead
5310                     case 'f': form = QLocalePrivate::DFDecimal; break;
5311                     case 'g': form = QLocalePrivate::DFSignificantDigits; break;
5312                     default: break;
5313                 }
5314                 subst = locale.d()->doubleToString(d, precision, form, width, flags);
5315                 ++c;
5316                 break;
5317             }
5318             case 'c': {
5319                 if (length_mod == lm_l)
5320                     subst = QChar((ushort) va_arg(ap, int));
5321                 else
5322                     subst = QLatin1Char((uchar) va_arg(ap, int));
5323                 ++c;
5324                 break;
5325             }
5326             case 's': {
5327                 if (length_mod == lm_l) {
5328                     const ushort *buff = va_arg(ap, const ushort*);
5329                     const ushort *ch = buff;
5330                     while (*ch != 0)
5331                         ++ch;
5332                     subst.setUtf16(buff, ch - buff);
5333                 } else
5334                     subst = QString::fromUtf8(va_arg(ap, const char*));
5335                 if (precision != -1)
5336                     subst.truncate(precision);
5337                 ++c;
5338                 break;
5339             }
5340             case 'p': {
5341                 void *arg = va_arg(ap, void*);
5342 #ifdef Q_OS_WIN64
5343                 quint64 i = reinterpret_cast<quint64>(arg);
5344 #else
5345                 quint64 i = reinterpret_cast<unsigned long>(arg);
5346 #endif
5347                 flags |= QLocalePrivate::Alternate;
5348                 subst = locale.d()->unsLongLongToString(i, precision, 16, width, flags);
5349                 ++c;
5350                 break;
5351             }
5352             case 'n':
5353                 switch (length_mod) {
5354                     case lm_hh: {
5355                         signed char *n = va_arg(ap, signed char*);
5356                         *n = result.length();
5357                         break;
5358                     }
5359                     case lm_h: {
5360                         short int *n = va_arg(ap, short int*);
5361                         *n = result.length();
5362                             break;
5363                     }
5364                     case lm_l: {
5365                         long int *n = va_arg(ap, long int*);
5366                         *n = result.length();
5367                         break;
5368                     }
5369                     case lm_ll: {
5370                         qint64 *n = va_arg(ap, qint64*);
5371                         volatile uint tmp = result.length(); // egcs-2.91.66 gets internal
5372                         *n = tmp;                             // compiler error without volatile
5373                         break;
5374                     }
5375                     default: {
5376                         int *n = va_arg(ap, int*);
5377                         *n = result.length();
5378                         break;
5379                     }
5380                 }
5381                 ++c;
5382                 break;
5383
5384             default: // bad escape, treat as non-escape text
5385                 for (const char *cc = escape_start; cc != c; ++cc)
5386                     result.append(QLatin1Char(*cc));
5387                 continue;
5388         }
5389
5390         if (flags & QLocalePrivate::LeftAdjusted)
5391             result.append(subst.leftJustified(width));
5392         else
5393             result.append(subst.rightJustified(width));
5394     }
5395
5396     *this = result;
5397
5398     return *this;
5399 }
5400
5401 /*!
5402     Returns the string converted to a \c{long long} using base \a
5403     base, which is 10 by default and must be between 2 and 36, or 0.
5404     Returns 0 if the conversion fails.
5405
5406     If a conversion error occurs, *\a{ok} is set to false; otherwise
5407     *\a{ok} is set to true.
5408
5409     If \a base is 0, the C language convention is used: If the string
5410     begins with "0x", base 16 is used; if the string begins with "0",
5411     base 8 is used; otherwise, base 10 is used.
5412
5413     The string conversion will always happen in the 'C' locale. For locale
5414     dependent conversion use QLocale::toLongLong()
5415
5416     Example:
5417
5418     \snippet doc/src/snippets/qstring/main.cpp 74
5419
5420     \sa number(), toULongLong(), toInt(), QLocale::toLongLong()
5421 */
5422
5423 qint64 QString::toLongLong(bool *ok, int base) const
5424 {
5425 #if defined(QT_CHECK_RANGE)
5426     if (base != 0 && (base < 2 || base > 36)) {
5427         qWarning("QString::toLongLong: Invalid base (%d)", base);
5428         base = 10;
5429     }
5430 #endif
5431
5432     QLocale c_locale(QLocale::C);
5433     return c_locale.d()->stringToLongLong(*this, base, ok, QLocalePrivate::FailOnGroupSeparators);
5434 }
5435
5436 /*!
5437     Returns the string converted to an \c{unsigned long long} using base \a
5438     base, which is 10 by default and must be between 2 and 36, or 0.
5439     Returns 0 if the conversion fails.
5440
5441     If a conversion error occurs, *\a{ok} is set to false; otherwise
5442     *\a{ok} is set to true.
5443
5444     If \a base is 0, the C language convention is used: If the string
5445     begins with "0x", base 16 is used; if the string begins with "0",
5446     base 8 is used; otherwise, base 10 is used.
5447
5448     The string conversion will always happen in the 'C' locale. For locale
5449     dependent conversion use QLocale::toULongLong()
5450
5451     Example:
5452
5453     \snippet doc/src/snippets/qstring/main.cpp 79
5454
5455     \sa number(), toLongLong(), QLocale::toULongLong()
5456 */
5457
5458 quint64 QString::toULongLong(bool *ok, int base) const
5459 {
5460 #if defined(QT_CHECK_RANGE)
5461     if (base != 0 && (base < 2 || base > 36)) {
5462         qWarning("QString::toULongLong: Invalid base (%d)", base);
5463         base = 10;
5464     }
5465 #endif
5466
5467     QLocale c_locale(QLocale::C);
5468     return c_locale.d()->stringToUnsLongLong(*this, base, ok, QLocalePrivate::FailOnGroupSeparators);
5469 }
5470
5471 /*!
5472     \fn long QString::toLong(bool *ok, int base) const
5473
5474     Returns the string converted to a \c long using base \a
5475     base, which is 10 by default and must be between 2 and 36, or 0.
5476     Returns 0 if the conversion fails.
5477
5478     If a conversion error occurs, *\a{ok} is set to false; otherwise
5479     *\a{ok} is set to true.
5480
5481     If \a base is 0, the C language convention is used: If the string
5482     begins with "0x", base 16 is used; if the string begins with "0",
5483     base 8 is used; otherwise, base 10 is used.
5484
5485     The string conversion will always happen in the 'C' locale. For locale
5486     dependent conversion use QLocale::toLong()
5487
5488     Example:
5489
5490     \snippet doc/src/snippets/qstring/main.cpp 73
5491
5492     \sa number(), toULong(), toInt(), QLocale::toLong()
5493 */
5494
5495 long QString::toLong(bool *ok, int base) const
5496 {
5497     qint64 v = toLongLong(ok, base);
5498     if (v < LONG_MIN || v > LONG_MAX) {
5499         if (ok)
5500             *ok = false;
5501         v = 0;
5502     }
5503     return (long)v;
5504 }
5505
5506 /*!
5507     \fn ulong QString::toULong(bool *ok, int base) const
5508
5509     Returns the string converted to an \c{unsigned long} using base \a
5510     base, which is 10 by default and must be between 2 and 36, or 0.
5511     Returns 0 if the conversion fails.
5512
5513     If a conversion error occurs, *\a{ok} is set to false; otherwise
5514     *\a{ok} is set to true.
5515
5516     If \a base is 0, the C language convention is used: If the string
5517     begins with "0x", base 16 is used; if the string begins with "0",
5518     base 8 is used; otherwise, base 10 is used.
5519
5520     The string conversion will always happen in the 'C' locale. For locale
5521     dependent conversion use QLocale::toULong()
5522
5523     Example:
5524
5525     \snippet doc/src/snippets/qstring/main.cpp 78
5526
5527     \sa number(), QLocale::toULong()
5528 */
5529
5530 ulong QString::toULong(bool *ok, int base) const
5531 {
5532     quint64 v = toULongLong(ok, base);
5533     if (v > ULONG_MAX) {
5534         if (ok)
5535             *ok = false;
5536         v = 0;
5537     }
5538     return (ulong)v;
5539 }
5540
5541
5542 /*!
5543     Returns the string converted to an \c int using base \a
5544     base, which is 10 by default and must be between 2 and 36, or 0.
5545     Returns 0 if the conversion fails.
5546
5547     If a conversion error occurs, *\a{ok} is set to false; otherwise
5548     *\a{ok} is set to true.
5549
5550     If \a base is 0, the C language convention is used: If the string
5551     begins with "0x", base 16 is used; if the string begins with "0",
5552     base 8 is used; otherwise, base 10 is used.
5553
5554     The string conversion will always happen in the 'C' locale. For locale
5555     dependent conversion use QLocale::toInt()
5556
5557     Example:
5558
5559     \snippet doc/src/snippets/qstring/main.cpp 72
5560
5561     \sa number(), toUInt(), toDouble(), QLocale::toInt()
5562 */
5563
5564 int QString::toInt(bool *ok, int base) const
5565 {
5566     qint64 v = toLongLong(ok, base);
5567     if (v < INT_MIN || v > INT_MAX) {
5568         if (ok)
5569             *ok = false;
5570         v = 0;
5571     }
5572     return v;
5573 }
5574
5575 /*!
5576     Returns the string converted to an \c{unsigned int} using base \a
5577     base, which is 10 by default and must be between 2 and 36, or 0.
5578     Returns 0 if the conversion fails.
5579
5580     If a conversion error occurs, *\a{ok} is set to false; otherwise
5581     *\a{ok} is set to true.
5582
5583     If \a base is 0, the C language convention is used: If the string
5584     begins with "0x", base 16 is used; if the string begins with "0",
5585     base 8 is used; otherwise, base 10 is used.
5586
5587     The string conversion will always happen in the 'C' locale. For locale
5588     dependent conversion use QLocale::toUInt()
5589
5590     Example:
5591
5592     \snippet doc/src/snippets/qstring/main.cpp 77
5593
5594     \sa number(), toInt(), QLocale::toUInt()
5595 */
5596
5597 uint QString::toUInt(bool *ok, int base) const
5598 {
5599     quint64 v = toULongLong(ok, base);
5600     if (v > UINT_MAX) {
5601         if (ok)
5602             *ok = false;
5603         v = 0;
5604     }
5605     return (uint)v;
5606 }
5607
5608 /*!
5609     Returns the string converted to a \c short using base \a
5610     base, which is 10 by default and must be between 2 and 36, or 0.
5611     Returns 0 if the conversion fails.
5612
5613     If a conversion error occurs, *\a{ok} is set to false; otherwise
5614     *\a{ok} is set to true.
5615
5616     If \a base is 0, the C language convention is used: If the string
5617     begins with "0x", base 16 is used; if the string begins with "0",
5618     base 8 is used; otherwise, base 10 is used.
5619
5620     The string conversion will always happen in the 'C' locale. For locale
5621     dependent conversion use QLocale::toShort()
5622
5623     Example:
5624
5625     \snippet doc/src/snippets/qstring/main.cpp 76
5626
5627     \sa number(), toUShort(), toInt(), QLocale::toShort()
5628 */
5629
5630 short QString::toShort(bool *ok, int base) const
5631 {
5632     long v = toLongLong(ok, base);
5633     if (v < SHRT_MIN || v > SHRT_MAX) {
5634         if (ok)
5635             *ok = false;
5636         v = 0;
5637     }
5638     return (short)v;
5639 }
5640
5641 /*!
5642     Returns the string converted to an \c{unsigned short} using base \a
5643     base, which is 10 by default and must be between 2 and 36, or 0.
5644     Returns 0 if the conversion fails.
5645
5646     If a conversion error occurs, *\a{ok} is set to false; otherwise
5647     *\a{ok} is set to true.
5648
5649     If \a base is 0, the C language convention is used: If the string
5650     begins with "0x", base 16 is used; if the string begins with "0",
5651     base 8 is used; otherwise, base 10 is used.
5652
5653     The string conversion will always happen in the 'C' locale. For locale
5654     dependent conversion use QLocale::toUShort()
5655
5656     Example:
5657
5658     \snippet doc/src/snippets/qstring/main.cpp 80
5659
5660     \sa number(), toShort(), QLocale::toUShort()
5661 */
5662
5663 ushort QString::toUShort(bool *ok, int base) const
5664 {
5665     ulong v = toULongLong(ok, base);
5666     if (v > USHRT_MAX) {
5667         if (ok)
5668             *ok = false;
5669         v = 0;
5670     }
5671     return (ushort)v;
5672 }
5673
5674
5675 /*!
5676     Returns the string converted to a \c double value.
5677
5678     Returns 0.0 if the conversion fails.
5679
5680     If a conversion error occurs, \c{*}\a{ok} is set to false;
5681     otherwise \c{*}\a{ok} is set to true.
5682
5683     \snippet doc/src/snippets/qstring/main.cpp 66
5684
5685     Various string formats for floating point numbers can be converted
5686     to double values:
5687
5688     \snippet doc/src/snippets/qstring/main.cpp 67
5689
5690     The string conversion will always happen in the 'C' locale. For locale
5691     dependent conversion use QLocale::toDouble()
5692
5693     \snippet doc/src/snippets/qstring/main.cpp 68
5694
5695     For historic reasons, this function does not handle
5696     thousands group separators. If you need to convert such numbers,
5697     use QLocale::toDouble().
5698
5699     \snippet doc/src/snippets/qstring/main.cpp 69
5700
5701     \sa number() QLocale::setDefault() QLocale::toDouble() trimmed()
5702 */
5703
5704 double QString::toDouble(bool *ok) const
5705 {
5706     QLocale c_locale(QLocale::C);
5707     return c_locale.d()->stringToDouble(*this, ok, QLocalePrivate::FailOnGroupSeparators);
5708 }
5709
5710 /*!
5711     Returns the string converted to a \c float value.
5712
5713     If a conversion error occurs, *\a{ok} is set to false; otherwise
5714     *\a{ok} is set to true. Returns 0.0 if the conversion fails.
5715
5716     The string conversion will always happen in the 'C' locale. For locale
5717     dependent conversion use QLocale::toFloat()
5718
5719     Example:
5720
5721     \snippet doc/src/snippets/qstring/main.cpp 71
5722
5723     \sa number(), toDouble(), toInt(), QLocale::toFloat()
5724 */
5725
5726 #define QT_MAX_FLOAT 3.4028234663852886e+38
5727
5728 float QString::toFloat(bool *ok) const
5729 {
5730     bool myOk;
5731     double d = toDouble(&myOk);
5732     if (!myOk || d > QT_MAX_FLOAT || d < -QT_MAX_FLOAT) {
5733         if (ok != 0)
5734             *ok = false;
5735         return 0.0;
5736     }
5737     if (ok != 0)
5738         *ok = true;
5739     return (float) d;
5740 }
5741
5742 /*! \fn QString &QString::setNum(int n, int base)
5743
5744     Sets the string to the printed value of \a n in the specified \a
5745     base, and returns a reference to the string.
5746
5747     The base is 10 by default and must be between 2 and 36. For bases
5748     other than 10, \a n is treated as an unsigned integer.
5749
5750     \snippet doc/src/snippets/qstring/main.cpp 56
5751
5752    The formatting always uses QLocale::C, i.e., English/UnitedStates.
5753    To get a localized string representation of a number, use
5754    QLocale::toString() with the appropriate locale.
5755 */
5756
5757 /*! \fn QString &QString::setNum(uint n, int base)
5758
5759     \overload
5760 */
5761
5762 /*! \fn QString &QString::setNum(long n, int base)
5763
5764     \overload
5765 */
5766
5767 /*! \fn QString &QString::setNum(ulong n, int base)
5768
5769     \overload
5770 */
5771
5772 /*!
5773     \overload
5774 */
5775 QString &QString::setNum(qlonglong n, int base)
5776 {
5777 #if defined(QT_CHECK_RANGE)
5778     if (base < 2 || base > 36) {
5779         qWarning("QString::setNum: Invalid base (%d)", base);
5780         base = 10;
5781     }
5782 #endif
5783     QLocale locale(QLocale::C);
5784     *this = locale.d()->longLongToString(n, -1, base);
5785     return *this;
5786 }
5787
5788 /*!
5789     \overload
5790 */
5791 QString &QString::setNum(qulonglong n, int base)
5792 {
5793 #if defined(QT_CHECK_RANGE)
5794     if (base < 2 || base > 36) {
5795         qWarning("QString::setNum: Invalid base (%d)", base);
5796         base = 10;
5797     }
5798 #endif
5799     QLocale locale(QLocale::C);
5800     *this = locale.d()->unsLongLongToString(n, -1, base);
5801     return *this;
5802 }
5803
5804 /*! \fn QString &QString::setNum(short n, int base)
5805
5806     \overload
5807 */
5808
5809 /*! \fn QString &QString::setNum(ushort n, int base)
5810
5811     \overload
5812 */
5813
5814 /*!
5815     \fn QString &QString::setNum(double n, char format, int precision)
5816     \overload
5817
5818     Sets the string to the printed value of \a n, formatted according
5819     to the given \a format and \a precision, and returns a reference
5820     to the string.
5821
5822     The \a format can be 'f', 'F', 'e', 'E', 'g' or 'G' (see the
5823     arg() function documentation for an explanation of the formats).
5824
5825     The formatting always uses QLocale::C, i.e., English/UnitedStates.
5826     To get a localized string representation of a number, use
5827     QLocale::toString() with the appropriate locale.
5828 */
5829
5830 QString &QString::setNum(double n, char f, int prec)
5831 {
5832     QLocalePrivate::DoubleForm form = QLocalePrivate::DFDecimal;
5833     uint flags = 0;
5834
5835     if (qIsUpper(f))
5836         flags = QLocalePrivate::CapitalEorX;
5837     f = qToLower(f);
5838
5839     switch (f) {
5840         case 'f':
5841             form = QLocalePrivate::DFDecimal;
5842             break;
5843         case 'e':
5844             form = QLocalePrivate::DFExponent;
5845             break;
5846         case 'g':
5847             form = QLocalePrivate::DFSignificantDigits;
5848             break;
5849         default:
5850 #if defined(QT_CHECK_RANGE)
5851             qWarning("QString::setNum: Invalid format char '%c'", f);
5852 #endif
5853             break;
5854     }
5855
5856     QLocale locale(QLocale::C);
5857     *this = locale.d()->doubleToString(n, prec, form, -1, flags);
5858     return *this;
5859 }
5860
5861 /*!
5862     \fn QString &QString::setNum(float n, char format, int precision)
5863     \overload
5864
5865     Sets the string to the printed value of \a n, formatted according
5866     to the given \a format and \a precision, and returns a reference
5867     to the string.
5868
5869     The formatting always uses QLocale::C, i.e., English/UnitedStates.
5870     To get a localized string representation of a number, use
5871     QLocale::toString() with the appropriate locale.
5872 */
5873
5874
5875 /*!
5876     \fn QString QString::number(long n, int base)
5877
5878     Returns a string equivalent of the number \a n according to the
5879     specified \a base.
5880
5881     The base is 10 by default and must be between 2
5882     and 36. For bases other than 10, \a n is treated as an
5883     unsigned integer.
5884
5885     The formatting always uses QLocale::C, i.e., English/UnitedStates.
5886     To get a localized string representation of a number, use
5887     QLocale::toString() with the appropriate locale.
5888
5889     \snippet doc/src/snippets/qstring/main.cpp 35
5890
5891     \sa setNum()
5892 */
5893
5894 QString QString::number(long n, int base)
5895 {
5896     QString s;
5897     s.setNum(n, base);
5898     return s;
5899 }
5900
5901 /*!
5902   \fn QString QString::number(ulong n, int base)
5903
5904     \overload
5905 */
5906 QString QString::number(ulong n, int base)
5907 {
5908     QString s;
5909     s.setNum(n, base);
5910     return s;
5911 }
5912
5913 /*!
5914     \overload
5915 */
5916 QString QString::number(int n, int base)
5917 {
5918     QString s;
5919     s.setNum(n, base);
5920     return s;
5921 }
5922
5923 /*!
5924     \overload
5925 */
5926 QString QString::number(uint n, int base)
5927 {
5928     QString s;
5929     s.setNum(n, base);
5930     return s;
5931 }
5932
5933 /*!
5934     \overload
5935 */
5936 QString QString::number(qlonglong n, int base)
5937 {
5938     QString s;
5939     s.setNum(n, base);
5940     return s;
5941 }
5942
5943 /*!
5944     \overload
5945 */
5946 QString QString::number(qulonglong n, int base)
5947 {
5948     QString s;
5949     s.setNum(n, base);
5950     return s;
5951 }
5952
5953
5954 /*!
5955     \fn QString QString::number(double n, char format, int precision)
5956
5957     Returns a string equivalent of the number \a n, formatted
5958     according to the specified \a format and \a precision. See
5959     \l{Argument Formats} for details.
5960
5961     Unlike QLocale::toString(), this function does not honor the
5962     user's locale settings.
5963
5964     \sa setNum(), QLocale::toString()
5965 */
5966 QString QString::number(double n, char f, int prec)
5967 {
5968     QString s;
5969     s.setNum(n, f, prec);
5970     return s;
5971 }
5972
5973 /*!
5974     Splits the string into substrings wherever \a sep occurs, and
5975     returns the list of those strings. If \a sep does not match
5976     anywhere in the string, split() returns a single-element list
5977     containing this string.
5978
5979     \a cs specifies whether \a sep should be matched case
5980     sensitively or case insensitively.
5981
5982     If \a behavior is QString::SkipEmptyParts, empty entries don't
5983     appear in the result. By default, empty entries are kept.
5984
5985     Example:
5986
5987     \snippet doc/src/snippets/qstring/main.cpp 62
5988
5989     \sa QStringList::join(), section()
5990 */
5991 QStringList QString::split(const QString &sep, SplitBehavior behavior, Qt::CaseSensitivity cs) const
5992 {
5993     QStringList list;
5994     int start = 0;
5995     int extra = 0;
5996     int end;
5997     while ((end = indexOf(sep, start + extra, cs)) != -1) {
5998         if (start != end || behavior == KeepEmptyParts)
5999             list.append(mid(start, end - start));
6000         start = end + sep.size();
6001         extra = (sep.size() == 0 ? 1 : 0);
6002     }
6003     if (start != size() || behavior == KeepEmptyParts)
6004         list.append(mid(start));
6005     return list;
6006 }
6007
6008 /*!
6009     \overload
6010 */
6011 QStringList QString::split(QChar sep, SplitBehavior behavior, Qt::CaseSensitivity cs) const
6012 {
6013     QStringList list;
6014     int start = 0;
6015     int end;
6016     while ((end = indexOf(sep, start, cs)) != -1) {
6017         if (start != end || behavior == KeepEmptyParts)
6018             list.append(mid(start, end - start));
6019         start = end + 1;
6020     }
6021     if (start != size() || behavior == KeepEmptyParts)
6022         list.append(mid(start));
6023     return list;
6024 }
6025
6026 #ifndef QT_NO_REGEXP
6027 /*!
6028     \overload
6029
6030     Splits the string into substrings wherever the regular expression
6031     \a rx matches, and returns the list of those strings. If \a rx
6032     does not match anywhere in the string, split() returns a
6033     single-element list containing this string.
6034
6035     Here's an example where we extract the words in a sentence
6036     using one or more whitespace characters as the separator:
6037
6038     \snippet doc/src/snippets/qstring/main.cpp 59
6039
6040     Here's a similar example, but this time we use any sequence of
6041     non-word characters as the separator:
6042
6043     \snippet doc/src/snippets/qstring/main.cpp 60
6044
6045     Here's a third example where we use a zero-length assertion,
6046     \bold{\\b} (word boundary), to split the string into an
6047     alternating sequence of non-word and word tokens:
6048
6049     \snippet doc/src/snippets/qstring/main.cpp 61
6050
6051     \sa QStringList::join(), section()
6052 */
6053 QStringList QString::split(const QRegExp &rx, SplitBehavior behavior) const
6054 {
6055     QRegExp rx2(rx);
6056     QStringList list;
6057     int start = 0;
6058     int extra = 0;
6059     int end;
6060     while ((end = rx2.indexIn(*this, start + extra)) != -1) {
6061         int matchedLen = rx2.matchedLength();
6062         if (start != end || behavior == KeepEmptyParts)
6063             list.append(mid(start, end - start));
6064         start = end + matchedLen;
6065         extra = (matchedLen == 0) ? 1 : 0;
6066     }
6067     if (start != size() || behavior == KeepEmptyParts)
6068         list.append(mid(start));
6069     return list;
6070 }
6071 #endif
6072
6073 /*!
6074     \enum QString::NormalizationForm
6075
6076     This enum describes the various normalized forms of Unicode text.
6077
6078     \value NormalizationForm_D  Canonical Decomposition
6079     \value NormalizationForm_C  Canonical Decomposition followed by Canonical Composition
6080     \value NormalizationForm_KD  Compatibility Decomposition
6081     \value NormalizationForm_KC  Compatibility Decomposition followed by Canonical Composition
6082
6083     \sa normalized(),
6084         {http://www.unicode.org/reports/tr15/}{Unicode Standard Annex #15}
6085 */
6086
6087 /*!
6088     \fn QString QString::normalized(NormalizationForm mode) const
6089     Returns the string in the given Unicode normalization \a mode.
6090 */
6091 QString QString::normalized(QString::NormalizationForm mode) const
6092 {
6093     return normalized(mode, UNICODE_DATA_VERSION);
6094 }
6095
6096 /*!
6097     \since 4.5
6098
6099     Returns a copy of this string repeated the specified number of \a times.
6100
6101     If \a times is less than 1, an empty string is returned.
6102
6103     Example:
6104
6105     \code
6106         QString str("ab");
6107         str.repeated(4);            // returns "abababab"
6108     \endcode
6109 */
6110 QString QString::repeated(int times) const
6111 {
6112     if (d->size == 0)
6113         return *this;
6114
6115     if (times <= 1) {
6116         if (times == 1)
6117             return *this;
6118         return QString();
6119     }
6120
6121     const int resultSize = times * d->size;
6122
6123     QString result;
6124     result.reserve(resultSize);
6125     if (int(result.d->alloc) != resultSize)
6126         return QString(); // not enough memory
6127
6128     memcpy(result.d->data(), d->data(), d->size * sizeof(ushort));
6129
6130     int sizeSoFar = d->size;
6131     ushort *end = result.d->data() + sizeSoFar;
6132
6133     const int halfResultSize = resultSize >> 1;
6134     while (sizeSoFar <= halfResultSize) {
6135         memcpy(end, result.d->data(), sizeSoFar * sizeof(ushort));
6136         end += sizeSoFar;
6137         sizeSoFar <<= 1;
6138     }
6139     memcpy(end, result.d->data(), (resultSize - sizeSoFar) * sizeof(ushort));
6140     result.d->data()[resultSize] = '\0';
6141     result.d->size = resultSize;
6142     return result;
6143 }
6144
6145 void qt_string_normalize(QString *data, QString::NormalizationForm mode, QChar::UnicodeVersion version, int from);
6146 /*!
6147     \overload
6148     \fn QString QString::normalized(NormalizationForm mode, QChar::UnicodeVersion version) const
6149
6150     Returns the string in the given Unicode normalization \a mode,
6151     according to the given \a version of the Unicode standard.
6152 */
6153 QString QString::normalized(QString::NormalizationForm mode, QChar::UnicodeVersion version) const
6154 {
6155     QString copy = *this;
6156     qt_string_normalize(&copy, mode, version, 0);
6157     return copy;
6158 }
6159
6160 void qt_string_normalize(QString *data, QString::NormalizationForm mode, QChar::UnicodeVersion version, int from)
6161 {
6162     bool simple = true;
6163     const QChar *p = data->constData();
6164     int len = data->length();
6165     for (int i = from; i < len; ++i) {
6166         if (p[i].unicode() >= 0x80) {
6167             simple = false;
6168             break;
6169         }
6170     }
6171     if (simple)
6172         return;
6173
6174     if (version == QChar::Unicode_Unassigned) {
6175         version = UNICODE_DATA_VERSION;
6176     } else if (version != UNICODE_DATA_VERSION) {
6177         const QString &s = *data;
6178         QChar *d = 0;
6179         for (int i = 0; i < NumNormalizationCorrections; ++i) {
6180             const NormalizationCorrection &n = uc_normalization_corrections[i];
6181             if (n.version > version) {
6182                 int pos = from;
6183                 if (QChar::requiresSurrogates(n.ucs4)) {
6184                     ushort ucs4High = QChar::highSurrogate(n.ucs4);
6185                     ushort ucs4Low = QChar::lowSurrogate(n.ucs4);
6186                     ushort oldHigh = QChar::highSurrogate(n.old_mapping);
6187                     ushort oldLow = QChar::lowSurrogate(n.old_mapping);
6188                     while (pos < s.length() - 1) {
6189                         if (s.at(pos).unicode() == ucs4High && s.at(pos + 1).unicode() == ucs4Low) {
6190                             if (!d)
6191                                 d = data->data();
6192                             d[pos] = QChar(oldHigh);
6193                             d[++pos] = QChar(oldLow);
6194                         }
6195                         ++pos;
6196                     }
6197                 } else {
6198                     while (pos < s.length()) {
6199                         if (s.at(pos).unicode() == n.ucs4) {
6200                             if (!d)
6201                                 d = data->data();
6202                             d[pos] = QChar(n.old_mapping);
6203                         }
6204                         ++pos;
6205                     }
6206                 }
6207             }
6208         }
6209     }
6210     decomposeHelper(data, mode < QString::NormalizationForm_KD, version, from);
6211
6212     canonicalOrderHelper(data, version, from);
6213
6214     if (mode == QString::NormalizationForm_D || mode == QString::NormalizationForm_KD)
6215         return;
6216
6217     composeHelper(data, version, from);
6218 }
6219
6220
6221 struct ArgEscapeData
6222 {
6223     int min_escape;            // lowest escape sequence number
6224     int occurrences;           // number of occurrences of the lowest escape sequence number
6225     int locale_occurrences;    // number of occurrences of the lowest escape sequence number that
6226                                // contain 'L'
6227     int escape_len;            // total length of escape sequences which will be replaced
6228 };
6229
6230 static ArgEscapeData findArgEscapes(const QString &s)
6231 {
6232     const QChar *uc_begin = s.unicode();
6233     const QChar *uc_end = uc_begin + s.length();
6234
6235     ArgEscapeData d;
6236
6237     d.min_escape = INT_MAX;
6238     d.occurrences = 0;
6239     d.escape_len = 0;
6240     d.locale_occurrences = 0;
6241
6242     const QChar *c = uc_begin;
6243     while (c != uc_end) {
6244         while (c != uc_end && c->unicode() != '%')
6245             ++c;
6246
6247         if (c == uc_end)
6248             break;
6249         const QChar *escape_start = c;
6250         if (++c == uc_end)
6251             break;
6252
6253         bool locale_arg = false;
6254         if (c->unicode() == 'L') {
6255             locale_arg = true;
6256             if (++c == uc_end)
6257                 break;
6258         }
6259
6260         if (c->digitValue() == -1)
6261             continue;
6262
6263         int escape = c->digitValue();
6264         ++c;
6265
6266         if (c != uc_end && c->digitValue() != -1) {
6267             escape = (10 * escape) + c->digitValue();
6268             ++c;
6269         }
6270
6271         if (escape > d.min_escape)
6272             continue;
6273
6274         if (escape < d.min_escape) {
6275             d.min_escape = escape;
6276             d.occurrences = 0;
6277             d.escape_len = 0;
6278             d.locale_occurrences = 0;
6279         }
6280
6281         ++d.occurrences;
6282         if (locale_arg)
6283             ++d.locale_occurrences;
6284         d.escape_len += c - escape_start;
6285     }
6286     return d;
6287 }
6288
6289 static QString replaceArgEscapes(const QString &s, const ArgEscapeData &d, int field_width,
6290                                  const QString &arg, const QString &larg, QChar fillChar = QLatin1Char(' '))
6291 {
6292     const QChar *uc_begin = s.unicode();
6293     const QChar *uc_end = uc_begin + s.length();
6294
6295     int abs_field_width = qAbs(field_width);
6296     int result_len = s.length()
6297                      - d.escape_len
6298                      + (d.occurrences - d.locale_occurrences)
6299                      *qMax(abs_field_width, arg.length())
6300                      + d.locale_occurrences
6301                      *qMax(abs_field_width, larg.length());
6302
6303     QString result(result_len, Qt::Uninitialized);
6304     QChar *result_buff = (QChar*) result.unicode();
6305
6306     QChar *rc = result_buff;
6307     const QChar *c = uc_begin;
6308     int repl_cnt = 0;
6309     while (c != uc_end) {
6310         /* We don't have to check if we run off the end of the string with c,
6311            because as long as d.occurrences > 0 we KNOW there are valid escape
6312            sequences. */
6313
6314         const QChar *text_start = c;
6315
6316         while (c->unicode() != '%')
6317             ++c;
6318
6319         const QChar *escape_start = c++;
6320
6321         bool locale_arg = false;
6322         if (c->unicode() == 'L') {
6323             locale_arg = true;
6324             ++c;
6325         }
6326
6327         int escape = c->digitValue();
6328         if (escape != -1) {
6329             if (c + 1 != uc_end && (c + 1)->digitValue() != -1) {
6330                 escape = (10 * escape) + (c + 1)->digitValue();
6331                 ++c;
6332             }
6333         }
6334
6335         if (escape != d.min_escape) {
6336             memcpy(rc, text_start, (c - text_start)*sizeof(QChar));
6337             rc += c - text_start;
6338         }
6339         else {
6340             ++c;
6341
6342             memcpy(rc, text_start, (escape_start - text_start)*sizeof(QChar));
6343             rc += escape_start - text_start;
6344
6345             uint pad_chars;
6346             if (locale_arg)
6347                 pad_chars = qMax(abs_field_width, larg.length()) - larg.length();
6348             else
6349                 pad_chars = qMax(abs_field_width, arg.length()) - arg.length();
6350
6351             if (field_width > 0) { // left padded
6352                 for (uint i = 0; i < pad_chars; ++i)
6353                     (rc++)->unicode() = fillChar.unicode();
6354             }
6355
6356             if (locale_arg) {
6357                 memcpy(rc, larg.unicode(), larg.length()*sizeof(QChar));
6358                 rc += larg.length();
6359             }
6360             else {
6361                 memcpy(rc, arg.unicode(), arg.length()*sizeof(QChar));
6362                 rc += arg.length();
6363             }
6364
6365             if (field_width < 0) { // right padded
6366                 for (uint i = 0; i < pad_chars; ++i)
6367                     (rc++)->unicode() = fillChar.unicode();
6368             }
6369
6370             if (++repl_cnt == d.occurrences) {
6371                 memcpy(rc, c, (uc_end - c)*sizeof(QChar));
6372                 rc += uc_end - c;
6373                 Q_ASSERT(rc - result_buff == result_len);
6374                 c = uc_end;
6375             }
6376         }
6377     }
6378     Q_ASSERT(rc == result_buff + result_len);
6379
6380     return result;
6381 }
6382
6383 /*!
6384   Returns a copy of this string with the lowest numbered place marker
6385   replaced by string \a a, i.e., \c %1, \c %2, ..., \c %99.
6386
6387   \a fieldWidth specifies the minimum amount of space that argument \a
6388   a shall occupy. If \a a requires less space than \a fieldWidth, it
6389   is padded to \a fieldWidth with character \a fillChar.  A positive
6390   \a fieldWidth produces right-aligned text. A negative \a fieldWidth
6391   produces left-aligned text.
6392
6393   This example shows how we might create a \c status string for
6394   reporting progress while processing a list of files:
6395
6396   \snippet doc/src/snippets/qstring/main.cpp 11
6397
6398   First, \c arg(i) replaces \c %1. Then \c arg(total) replaces \c
6399   %2. Finally, \c arg(fileName) replaces \c %3.
6400
6401   One advantage of using arg() over sprintf() is that the order of the
6402   numbered place markers can change, if the application's strings are
6403   translated into other languages, but each arg() will still replace
6404   the lowest numbered unreplaced place marker, no matter where it
6405   appears. Also, if place marker \c %i appears more than once in the
6406   string, the arg() replaces all of them.
6407
6408   If there is no unreplaced place marker remaining, a warning message
6409   is output and the result is undefined. Place marker numbers must be
6410   in the range 1 to 99.
6411 */
6412 QString QString::arg(const QString &a, int fieldWidth, QChar fillChar) const
6413 {
6414     ArgEscapeData d = findArgEscapes(*this);
6415
6416     if (d.occurrences == 0) {
6417         qWarning("QString::arg: Argument missing: %s, %s", toLocal8Bit().data(),
6418                   a.toLocal8Bit().data());
6419         return *this;
6420     }
6421     return replaceArgEscapes(*this, d, fieldWidth, a, a, fillChar);
6422 }
6423
6424 /*!
6425   \fn QString QString::arg(const QString& a1, const QString& a2) const
6426   \overload arg()
6427
6428   This is the same as \c {str.arg(a1).arg(a2)}, except that the
6429   strings \a a1 and \a a2 are replaced in one pass. This can make a
6430   difference if \a a1 contains e.g. \c{%1}:
6431
6432   \snippet doc/src/snippets/qstring/main.cpp 13
6433 */
6434
6435 /*!
6436   \fn QString QString::arg(const QString& a1, const QString& a2, const QString& a3) const
6437   \overload arg()
6438
6439   This is the same as calling \c str.arg(a1).arg(a2).arg(a3), except
6440   that the strings \a a1, \a a2 and \a a3 are replaced in one pass.
6441 */
6442
6443 /*!
6444   \fn QString QString::arg(const QString& a1, const QString& a2, const QString& a3, const QString& a4) const
6445   \overload arg()
6446
6447   This is the same as calling \c
6448   {str.arg(a1).arg(a2).arg(a3).arg(a4)}, except that the strings \a
6449   a1, \a a2, \a a3 and \a a4 are replaced in one pass.
6450 */
6451
6452 /*!
6453   \fn QString QString::arg(const QString& a1, const QString& a2, const QString& a3, const QString& a4, const QString& a5) const
6454   \overload arg()
6455
6456   This is the same as calling \c
6457   {str.arg(a1).arg(a2).arg(a3).arg(a4).arg(a5)}, except that the strings
6458   \a a1, \a a2, \a a3, \a a4, and \a a5 are replaced in one pass.
6459 */
6460
6461 /*!
6462   \fn QString QString::arg(const QString& a1, const QString& a2, const QString& a3, const QString& a4, const QString& a5, const QString& a6) const
6463   \overload arg()
6464
6465   This is the same as calling \c
6466   {str.arg(a1).arg(a2).arg(a3).arg(a4).arg(a5).arg(a6))}, except that
6467   the strings \a a1, \a a2, \a a3, \a a4, \a a5, and \a a6 are
6468   replaced in one pass.
6469 */
6470
6471 /*!
6472   \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
6473   \overload arg()
6474
6475   This is the same as calling \c
6476   {str.arg(a1).arg(a2).arg(a3).arg(a4).arg(a5).arg(a6).arg(a7)},
6477   except that the strings \a a1, \a a2, \a a3, \a a4, \a a5, \a a6,
6478   and \a a7 are replaced in one pass.
6479 */
6480
6481 /*!
6482   \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
6483   \overload arg()
6484
6485   This is the same as calling \c
6486   {str.arg(a1).arg(a2).arg(a3).arg(a4).arg(a5).arg(a6).arg(a7).arg(a8)},
6487   except that the strings \a a1, \a a2, \a a3, \a a4, \a a5, \a a6, \a
6488   a7, and \a a8 are replaced in one pass.
6489 */
6490
6491 /*!
6492   \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
6493   \overload arg()
6494
6495   This is the same as calling \c
6496   {str.arg(a1).arg(a2).arg(a3).arg(a4).arg(a5).arg(a6).arg(a7).arg(a8).arg(a9)},
6497   except that the strings \a a1, \a a2, \a a3, \a a4, \a a5, \a a6, \a
6498   a7, \a a8, and \a a9 are replaced in one pass.
6499 */
6500
6501 /*! \fn QString QString::arg(int a, int fieldWidth, int base, QChar fillChar) const
6502   \overload arg()
6503
6504   The \a a argument is expressed in base \a base, which is 10 by
6505   default and must be between 2 and 36. For bases other than 10, \a a
6506   is treated as an unsigned integer.
6507
6508   \a fieldWidth specifies the minimum amount of space that \a a is
6509   padded to and filled with the character \a fillChar. A positive
6510   value produces right-aligned text; a negative value produces
6511   left-aligned text.
6512
6513   The '%' can be followed by an 'L', in which case the sequence is
6514   replaced with a localized representation of \a a. The conversion
6515   uses the default locale, set by QLocale::setDefault(). If no default
6516   locale was specified, the "C" locale is used. The 'L' flag is
6517   ignored if \a base is not 10.
6518
6519   \snippet doc/src/snippets/qstring/main.cpp 12
6520   \snippet doc/src/snippets/qstring/main.cpp 14
6521
6522   If \a fillChar is '0' (the number 0, ASCII 48), the locale's zero is
6523   used. For negative numbers, zero padding might appear before the
6524   minus sign.
6525 */
6526
6527 /*! \fn QString QString::arg(uint a, int fieldWidth, int base, QChar fillChar) const
6528   \overload arg()
6529
6530   The \a base argument specifies the base to use when converting the
6531   integer \a a into a string. The base must be between 2 and 36.
6532
6533   If \a fillChar is '0' (the number 0, ASCII 48), the locale's zero is
6534   used. For negative numbers, zero padding might appear before the
6535   minus sign.
6536 */
6537
6538 /*! \fn QString QString::arg(long a, int fieldWidth, int base, QChar fillChar) const
6539   \overload arg()
6540
6541   \a fieldWidth specifies the minimum amount of space that \a a is
6542   padded to and filled with the character \a fillChar. A positive
6543   value produces right-aligned text; a negative value produces
6544   left-aligned text.
6545
6546   The \a a argument is expressed in the given \a base, which is 10 by
6547   default and must be between 2 and 36.
6548
6549   The '%' can be followed by an 'L', in which case the sequence is
6550   replaced with a localized representation of \a a. The conversion
6551   uses the default locale. The default locale is determined from the
6552   system's locale settings at application startup. It can be changed
6553   using QLocale::setDefault(). The 'L' flag is ignored if \a base is
6554   not 10.
6555
6556   \snippet doc/src/snippets/qstring/main.cpp 12
6557   \snippet doc/src/snippets/qstring/main.cpp 14
6558
6559   If \a fillChar is '0' (the number 0, ASCII 48), the locale's zero is
6560   used. For negative numbers, zero padding might appear before the
6561   minus sign.
6562 */
6563
6564 /*! \fn QString QString::arg(ulong a, int fieldWidth, int base, QChar fillChar) const
6565   \overload arg()
6566
6567   \a fieldWidth specifies the minimum amount of space that \a a is
6568   padded to and filled with the character \a fillChar. A positive
6569   value produces right-aligned text; a negative value produces
6570   left-aligned text.
6571
6572   The \a base argument specifies the base to use when converting the
6573   integer \a a to a string. The base must be between 2 and 36, with 8
6574   giving octal, 10 decimal, and 16 hexadecimal numbers.
6575
6576   If \a fillChar is '0' (the number 0, ASCII 48), the locale's zero is
6577   used. For negative numbers, zero padding might appear before the
6578   minus sign.
6579 */
6580
6581 /*!
6582   \overload arg()
6583
6584   \a fieldWidth specifies the minimum amount of space that \a a is
6585   padded to and filled with the character \a fillChar. A positive
6586   value produces right-aligned text; a negative value produces
6587   left-aligned text.
6588
6589   The \a base argument specifies the base to use when converting the
6590   integer \a a into a string. The base must be between 2 and 36, with
6591   8 giving octal, 10 decimal, and 16 hexadecimal numbers.
6592
6593   If \a fillChar is '0' (the number 0, ASCII 48), the locale's zero is
6594   used. For negative numbers, zero padding might appear before the
6595   minus sign.
6596 */
6597 QString QString::arg(qlonglong a, int fieldWidth, int base, QChar fillChar) const
6598 {
6599     ArgEscapeData d = findArgEscapes(*this);
6600
6601     if (d.occurrences == 0) {
6602         qWarning() << "QString::arg: Argument missing:" << *this << ',' << a;
6603         return *this;
6604     }
6605
6606     unsigned flags = QLocalePrivate::NoFlags;
6607     if (fillChar == QLatin1Char('0'))
6608         flags = QLocalePrivate::ZeroPadded;
6609
6610     QString arg;
6611     if (d.occurrences > d.locale_occurrences)
6612         arg = QLocale::c().d()->longLongToString(a, -1, base, fieldWidth, flags);
6613
6614     QString locale_arg;
6615     if (d.locale_occurrences > 0) {
6616         QLocale locale;
6617         if (!locale.numberOptions() & QLocale::OmitGroupSeparator)
6618             flags |= QLocalePrivate::ThousandsGroup;
6619         locale_arg = locale.d()->longLongToString(a, -1, base, fieldWidth, flags);
6620     }
6621
6622     return replaceArgEscapes(*this, d, fieldWidth, arg, locale_arg, fillChar);
6623 }
6624
6625 /*!
6626   \overload arg()
6627
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
6631   left-aligned text.
6632
6633   The \a base argument specifies the base to use when converting the
6634   integer \a a into a string. \a base must be between 2 and 36, with 8
6635   giving octal, 10 decimal, and 16 hexadecimal numbers.
6636
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
6639   minus sign.
6640 */
6641 QString QString::arg(qulonglong a, int fieldWidth, int base, QChar fillChar) const
6642 {
6643     ArgEscapeData d = findArgEscapes(*this);
6644
6645     if (d.occurrences == 0) {
6646         qWarning() << "QString::arg: Argument missing:" << *this << ',' << a;
6647         return *this;
6648     }
6649
6650     unsigned flags = QLocalePrivate::NoFlags;
6651     if (fillChar == QLatin1Char('0'))
6652         flags = QLocalePrivate::ZeroPadded;
6653
6654     QString arg;
6655     if (d.occurrences > d.locale_occurrences)
6656         arg = QLocale::c().d()->unsLongLongToString(a, -1, base, fieldWidth, flags);
6657
6658     QString locale_arg;
6659     if (d.locale_occurrences > 0) {
6660         QLocale locale;
6661         if (!locale.numberOptions() & QLocale::OmitGroupSeparator)
6662             flags |= QLocalePrivate::ThousandsGroup;
6663         locale_arg = locale.d()->unsLongLongToString(a, -1, base, fieldWidth, flags);
6664     }
6665
6666     return replaceArgEscapes(*this, d, fieldWidth, arg, locale_arg, fillChar);
6667 }
6668
6669 /*!
6670   \overload arg()
6671
6672   \fn QString QString::arg(short a, int fieldWidth, int base, QChar fillChar) const
6673
6674   \a fieldWidth specifies the minimum amount of space that \a a is
6675   padded to and filled with the character \a fillChar. A positive
6676   value produces right-aligned text; a negative value produces
6677   left-aligned text.
6678
6679   The \a base argument specifies the base to use when converting the
6680   integer \a a into a string. The base must be between 2 and 36, with
6681   8 giving octal, 10 decimal, and 16 hexadecimal numbers.
6682
6683   If \a fillChar is '0' (the number 0, ASCII 48), the locale's zero is
6684   used. For negative numbers, zero padding might appear before the
6685   minus sign.
6686 */
6687
6688 /*!
6689   \fn QString QString::arg(ushort a, int fieldWidth, int base, QChar fillChar) const
6690   \overload arg()
6691
6692   \a fieldWidth specifies the minimum amount of space that \a a is
6693   padded to and filled with the character \a fillChar. A positive
6694   value produces right-aligned text; a negative value produces
6695   left-aligned text.
6696
6697   The \a base argument specifies the base to use when converting the
6698   integer \a a into a string. The base must be between 2 and 36, with
6699   8 giving octal, 10 decimal, and 16 hexadecimal numbers.
6700
6701   If \a fillChar is '0' (the number 0, ASCII 48), the locale's zero is
6702   used. For negative numbers, zero padding might appear before the
6703   minus sign.
6704 */
6705
6706 /*!
6707     \overload arg()
6708 */
6709 QString QString::arg(QChar a, int fieldWidth, QChar fillChar) const
6710 {
6711     QString c;
6712     c += a;
6713     return arg(c, fieldWidth, fillChar);
6714 }
6715
6716 /*!
6717   \overload arg()
6718
6719   The \a a argument is interpreted as a Latin-1 character.
6720 */
6721 QString QString::arg(char a, int fieldWidth, QChar fillChar) const
6722 {
6723     QString c;
6724     c += QLatin1Char(a);
6725     return arg(c, fieldWidth, fillChar);
6726 }
6727
6728 /*!
6729   \fn QString QString::arg(double a, int fieldWidth, char format, int precision, QChar fillChar) const
6730   \overload arg()
6731
6732   Argument \a a is formatted according to the specified \a format and
6733   \a precision. See \l{Argument Formats} for details.
6734
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
6738   left-aligned text.
6739
6740   \snippet doc/src/snippets/code/src_corelib_tools_qstring.cpp 2
6741
6742   The '%' can be followed by an 'L', in which case the sequence is
6743   replaced with a localized representation of \a a. The conversion
6744   uses the default locale, set by QLocale::setDefaultLocale(). If no
6745   default locale was specified, the "C" locale is used.
6746
6747   If \a fillChar is '0' (the number 0, ASCII 48), this function will
6748   use the locale's zero to pad. For negative numbers, the zero padding
6749   will probably appear before the minus sign.
6750
6751   \sa QLocale::toString()
6752 */
6753 QString QString::arg(double a, int fieldWidth, char fmt, int prec, QChar fillChar) const
6754 {
6755     ArgEscapeData d = findArgEscapes(*this);
6756
6757     if (d.occurrences == 0) {
6758         qWarning("QString::arg: Argument missing: %s, %g", toLocal8Bit().data(), a);
6759         return *this;
6760     }
6761
6762     unsigned flags = QLocalePrivate::NoFlags;
6763     if (fillChar == QLatin1Char('0'))
6764         flags = QLocalePrivate::ZeroPadded;
6765
6766     if (qIsUpper(fmt))
6767         flags |= QLocalePrivate::CapitalEorX;
6768     fmt = qToLower(fmt);
6769
6770     QLocalePrivate::DoubleForm form = QLocalePrivate::DFDecimal;
6771     switch (fmt) {
6772     case 'f':
6773         form = QLocalePrivate::DFDecimal;
6774         break;
6775     case 'e':
6776         form = QLocalePrivate::DFExponent;
6777         break;
6778     case 'g':
6779         form = QLocalePrivate::DFSignificantDigits;
6780         break;
6781     default:
6782 #if defined(QT_CHECK_RANGE)
6783         qWarning("QString::arg: Invalid format char '%c'", fmt);
6784 #endif
6785         break;
6786     }
6787
6788     QString arg;
6789     if (d.occurrences > d.locale_occurrences)
6790         arg = QLocale::c().d()->doubleToString(a, prec, form, fieldWidth, flags);
6791
6792     QString locale_arg;
6793     if (d.locale_occurrences > 0) {
6794         QLocale locale;
6795
6796         if (!locale.numberOptions() & QLocale::OmitGroupSeparator)
6797             flags |= QLocalePrivate::ThousandsGroup;
6798         locale_arg = locale.d()->doubleToString(a, prec, form, fieldWidth, flags);
6799     }
6800
6801     return replaceArgEscapes(*this, d, fieldWidth, arg, locale_arg, fillChar);
6802 }
6803
6804 static int getEscape(const QChar *uc, int *pos, int len, int maxNumber = 999)
6805 {
6806     int i = *pos;
6807     ++i;
6808     if (i < len && uc[i] == QLatin1Char('L'))
6809         ++i;
6810     if (i < len) {
6811         int escape = uc[i].unicode() - '0';
6812         if (uint(escape) >= 10U)
6813             return -1;
6814         ++i;
6815         while (i < len) {
6816             int digit = uc[i].unicode() - '0';
6817             if (uint(digit) >= 10U)
6818                 break;
6819             escape = (escape * 10) + digit;
6820             ++i;
6821         }
6822         if (escape <= maxNumber) {
6823             *pos = i;
6824             return escape;
6825         }
6826     }
6827     return -1;
6828 }
6829
6830 QString QString::multiArg(int numArgs, const QString **args) const
6831 {
6832     QString result;
6833     QMap<int, int> numbersUsed;
6834     const QChar *uc = (const QChar *) d->data();
6835     const int len = d->size;
6836     const int end = len - 1;
6837     int lastNumber = -1;
6838     int i = 0;
6839
6840     // populate the numbersUsed map with the %n's that actually occur in the string
6841     while (i < end) {
6842         if (uc[i] == QLatin1Char('%')) {
6843             int number = getEscape(uc, &i, len);
6844             if (number != -1) {
6845                 numbersUsed.insert(number, -1);
6846                 continue;
6847             }
6848         }
6849         ++i;
6850     }
6851
6852     // assign an argument number to each of the %n's
6853     QMap<int, int>::iterator j = numbersUsed.begin();
6854     QMap<int, int>::iterator jend = numbersUsed.end();
6855     int arg = 0;
6856     while (j != jend && arg < numArgs) {
6857         *j = arg++;
6858         lastNumber = j.key();
6859         ++j;
6860     }
6861
6862     // sanity
6863     if (numArgs > arg) {
6864         qWarning("QString::arg: %d argument(s) missing in %s", numArgs - arg, toLocal8Bit().data());
6865         numArgs = arg;
6866     }
6867
6868     i = 0;
6869     while (i < len) {
6870         if (uc[i] == QLatin1Char('%') && i != end) {
6871             int number = getEscape(uc, &i, len, lastNumber);
6872             int arg = numbersUsed[number];
6873             if (number != -1 && arg != -1) {
6874                 result += *args[arg];
6875                 continue;
6876             }
6877         }
6878         result += uc[i++];
6879     }
6880     return result;
6881 }
6882
6883
6884 /*! \fn bool QString::isSimpleText() const
6885
6886     \internal
6887 */
6888 bool QString::isSimpleText() const
6889 {
6890     const ushort *p = d->data();
6891     const ushort * const end = p + d->size;
6892     while (p < end) {
6893         ushort uc = *p;
6894         // sort out regions of complex text formatting
6895         if (uc > 0x058f && (uc < 0x1100 || uc > 0xfb0f)) {
6896             return false;
6897         }
6898         p++;
6899     }
6900
6901     return true;
6902 }
6903
6904 /*! \fn bool QString::isRightToLeft() const
6905
6906     Returns true if the string is read right to left.
6907 */
6908 bool QString::isRightToLeft() const
6909 {
6910     const ushort *p = d->data();
6911     const ushort * const end = p + d->size;
6912     while (p < end) {
6913         switch(QChar::direction(*p))
6914         {
6915         case QChar::DirL:
6916             return false;
6917         case QChar::DirR:
6918         case QChar::DirAL:
6919             return true;
6920         default:
6921             break;
6922         }
6923         ++p;
6924     }
6925     return false;
6926 }
6927
6928 /*! \fn QChar *QString::data()
6929
6930     Returns a pointer to the data stored in the QString. The pointer
6931     can be used to access and modify the characters that compose the
6932     string. For convenience, the data is '\\0'-terminated.
6933
6934     Example:
6935
6936     \snippet doc/src/snippets/qstring/main.cpp 19
6937
6938     Note that the pointer remains valid only as long as the string is
6939     not modified by other means. For read-only access, constData() is
6940     faster because it never causes a \l{deep copy} to occur.
6941
6942     \sa constData(), operator[]()
6943 */
6944
6945 /*! \fn const QChar *QString::data() const
6946
6947     \overload
6948 */
6949
6950 /*! \fn const QChar *QString::constData() const
6951
6952     Returns a pointer to the data stored in the QString. The pointer
6953     can be used to access the characters that compose the string. For
6954     convenience, the data is '\\0'-terminated.
6955
6956     Note that the pointer remains valid only as long as the string is
6957     not modified.
6958
6959     \sa data(), operator[]()
6960 */
6961
6962 /*! \fn void QString::push_front(const QString &other)
6963
6964     This function is provided for STL compatibility, prepending the
6965     given \a other string to the beginning of this string. It is
6966     equivalent to \c prepend(other).
6967
6968     \sa prepend()
6969 */
6970
6971 /*! \fn void QString::push_front(QChar ch)
6972
6973     \overload
6974
6975     Prepends the given \a ch character to the beginning of this string.
6976 */
6977
6978 /*! \fn void QString::push_back(const QString &other)
6979
6980     This function is provided for STL compatibility, appending the
6981     given \a other string onto the end of this string. It is
6982     equivalent to \c append(other).
6983
6984     \sa append()
6985 */
6986
6987 /*! \fn void QString::push_back(QChar ch)
6988
6989     \overload
6990
6991     Appends the given \a ch character onto the end of this string.
6992 */
6993
6994 /*!
6995     \fn std::string QString::toStdString() const
6996
6997     Returns a std::string object with the data contained in this
6998     QString. The Unicode data is converted into 8-bit characters using
6999     the toAscii() function.
7000
7001     This operator is mostly useful to pass a QString to a function
7002     that accepts a std::string object.
7003
7004     If the QString contains Unicode characters that the
7005     QTextCodec::codecForCStrings() codec cannot handle, using this operator
7006     can lead to loss of information.
7007
7008     This operator is only available if Qt is configured with STL
7009     compatibility enabled.
7010
7011     \sa toAscii(), toLatin1(), toUtf8(), toLocal8Bit()
7012 */
7013
7014 /*!
7015     Constructs a QString that uses the first \a size Unicode characters
7016     in the array \a unicode. The data in \a unicode is \e not
7017     copied. The caller must be able to guarantee that \a unicode will
7018     not be deleted or modified as long as the QString (or an
7019     unmodified copy of it) exists.
7020
7021     Any attempts to modify the QString or copies of it will cause it
7022     to create a deep copy of the data, ensuring that the raw data
7023     isn't modified.
7024
7025     Here's an example of how we can use a QRegExp on raw data in
7026     memory without requiring to copy the data into a QString:
7027
7028     \snippet doc/src/snippets/qstring/main.cpp 22
7029     \snippet doc/src/snippets/qstring/main.cpp 23
7030
7031     \warning A string created with fromRawData() is \e not
7032     '\\0'-terminated, unless the raw data contains a '\\0' character
7033     at position \a size. This means unicode() will \e not return a
7034     '\\0'-terminated string (although utf16() does, at the cost of
7035     copying the raw data).
7036
7037     \sa fromUtf16(), setRawData()
7038 */
7039 QString QString::fromRawData(const QChar *unicode, int size)
7040 {
7041     Data *x;
7042     if (!unicode) {
7043         x = const_cast<Data *>(&shared_null.str);
7044     } else if (!size) {
7045         x = const_cast<Data *>(&shared_empty.str);
7046     } else {
7047         x = static_cast<Data *>(::malloc(sizeof(Data) + sizeof(ushort)));
7048         Q_CHECK_PTR(x);
7049         x->ref.initializeOwned();
7050         x->size = size;
7051         x->alloc = 0;
7052         x->capacityReserved = false;
7053         x->offset = (const ushort *)unicode - (x->d + sizeof(qptrdiff)/sizeof(ushort));
7054     }
7055     return QString(x, 0);
7056 }
7057
7058 /*!
7059     \since 4.7
7060
7061     Resets the QString to use the first \a size Unicode characters
7062     in the array \a unicode. The data in \a unicode is \e not
7063     copied. The caller must be able to guarantee that \a unicode will
7064     not be deleted or modified as long as the QString (or an
7065     unmodified copy of it) exists.
7066
7067     This function can be used instead of fromRawData() to re-use
7068     existings QString objects to save memory re-allocations.
7069
7070     \sa fromRawData()
7071 */
7072 QString &QString::setRawData(const QChar *unicode, int size)
7073 {
7074     if (d->ref.isShared() || d->alloc) {
7075         *this = fromRawData(unicode, size);
7076     } else {
7077         if (unicode) {
7078             d->size = size;
7079             d->offset = (const ushort *)unicode - (d->d + sizeof(qptrdiff)/sizeof(ushort));
7080         } else {
7081             d->offset = 0;
7082             d->size = 0;
7083         }
7084     }
7085     return *this;
7086 }
7087
7088 /*! \class QLatin1String
7089     \brief The QLatin1String class provides a thin wrapper around an US-ASCII/Latin-1 encoded string literal.
7090
7091     \ingroup string-processing
7092     \reentrant
7093
7094     Many of QString's member functions are overloaded to accept
7095     \c{const char *} instead of QString. This includes the copy
7096     constructor, the assignment operator, the comparison operators,
7097     and various other functions such as \link QString::insert()
7098     insert() \endlink, \link QString::replace() replace()\endlink,
7099     and \link QString::indexOf() indexOf()\endlink. These functions
7100     are usually optimized to avoid constructing a QString object for
7101     the \c{const char *} data. For example, assuming \c str is a
7102     QString,
7103
7104     \snippet doc/src/snippets/code/src_corelib_tools_qstring.cpp 3
7105
7106     is much faster than
7107
7108     \snippet doc/src/snippets/code/src_corelib_tools_qstring.cpp 4
7109
7110     because it doesn't construct four temporary QString objects and
7111     make a deep copy of the character data.
7112
7113     Applications that define \c QT_NO_CAST_FROM_ASCII (as explained
7114     in the QString documentation) don't have access to QString's
7115     \c{const char *} API. To provide an efficient way of specifying
7116     constant Latin-1 strings, Qt provides the QLatin1String, which is
7117     just a very thin wrapper around a \c{const char *}. Using
7118     QLatin1String, the example code above becomes
7119
7120     \snippet doc/src/snippets/code/src_corelib_tools_qstring.cpp 5
7121
7122     This is a bit longer to type, but it provides exactly the same
7123     benefits as the first version of the code, and is faster than
7124     converting the Latin-1 strings using QString::fromLatin1().
7125
7126     Thanks to the QString(const QLatin1String &) constructor,
7127     QLatin1String can be used everywhere a QString is expected. For
7128     example:
7129
7130     \snippet doc/src/snippets/code/src_corelib_tools_qstring.cpp 6
7131
7132     \sa QString, QLatin1Char, QStringLiteral
7133 */
7134
7135 /*! \fn QLatin1String::QLatin1String(const char *str)
7136
7137     Constructs a QLatin1String object that stores \a str. Note that if
7138     \a str is 0, an empty string is created; this case is handled by
7139     QString.
7140
7141     The string data is \e not copied. The caller must be able to
7142     guarantee that \a str will not be deleted or modified as long as
7143     the QLatin1String object exists.
7144
7145     \sa latin1()
7146 */
7147
7148 /*! \fn QLatin1String::QLatin1String(const char *str, int size)
7149
7150     Constructs a QLatin1String object that stores \a str with \a size.
7151     Note that if \a str is 0, an empty string is created; this case
7152     is handled by QString.
7153
7154     The string data is \e not copied. The caller must be able to
7155     guarantee that \a str will not be deleted or modified as long as
7156     the QLatin1String object exists.
7157
7158     \sa latin1()
7159 */
7160
7161 /*! \fn const char *QLatin1String::latin1() const
7162
7163     Returns the Latin-1 string stored in this object.
7164 */
7165
7166 /*! \fn int QLatin1String::size() const
7167
7168     Returns the size of the Latin-1 string stored in this object.
7169 */
7170
7171 /*! \fn bool QLatin1String::operator==(const QString &other) const
7172
7173     Returns true if this string is equal to string \a other;
7174     otherwise returns false.
7175
7176     The comparison is based exclusively on the numeric Unicode values
7177     of the characters and is very fast, but is not what a human would
7178     expect. Consider sorting user-interface strings with
7179     QString::localeAwareCompare().
7180 */
7181
7182 /*!
7183     \fn bool QLatin1String::operator==(const char *other) const
7184     \since 4.3
7185     \overload
7186
7187     The \a other const char pointer is converted to a QString using
7188     the QString::fromAscii() function.
7189
7190     You can disable this operator by defining \c
7191     QT_NO_CAST_FROM_ASCII when you compile your applications. This
7192     can be useful if you want to ensure that all user-visible strings
7193     go through QObject::tr(), for example.
7194 */
7195
7196 /*! \fn bool QLatin1String::operator!=(const QString &other) const
7197
7198     Returns true if this string is not equal to string \a other;
7199     otherwise returns false.
7200
7201     The comparison is based exclusively on the numeric Unicode values
7202     of the characters and is very fast, but is not what a human would
7203     expect. Consider sorting user-interface strings with
7204     QString::localeAwareCompare().
7205 */
7206
7207 /*!
7208     \fn bool QLatin1String::operator!=(const char *other) const
7209     \since 4.3
7210     \overload operator!=()
7211
7212     The \a other const char pointer is converted to a QString using
7213     the QString::fromAscii() function.
7214
7215     You can disable this operator by defining \c
7216     QT_NO_CAST_FROM_ASCII when you compile your applications. This
7217     can be useful if you want to ensure that all user-visible strings
7218     go through QObject::tr(), for example.
7219 */
7220
7221 /*!
7222     \fn bool QLatin1String::operator>(const QString &other) const
7223
7224     Returns true if this string is lexically greater than string \a
7225     other; otherwise returns false.
7226
7227     The comparison is based exclusively on the numeric Unicode values
7228     of the characters and is very fast, but is not what a human would
7229     expect. Consider sorting user-interface strings with
7230     QString::localeAwareCompare().
7231 */
7232
7233 /*!
7234     \fn bool QLatin1String::operator>(const char *other) const
7235     \since 4.3
7236     \overload
7237
7238     The \a other const char pointer is converted to a QString using
7239     the QString::fromAscii() function.
7240
7241     You can disable this operator by defining \c QT_NO_CAST_FROM_ASCII
7242     when you compile your applications. This can be useful if you want
7243     to ensure that all user-visible strings go through QObject::tr(),
7244     for example.
7245 */
7246
7247 /*!
7248     \fn bool QLatin1String::operator<(const QString &other) const
7249
7250     Returns true if this string is lexically less than the \a other
7251     string; otherwise returns false.
7252
7253     The comparison is based exclusively on the numeric Unicode values
7254     of the characters and is very fast, but is not what a human would
7255     expect. Consider sorting user-interface strings using the
7256     QString::localeAwareCompare() function.
7257 */
7258
7259 /*!
7260     \fn bool QLatin1String::operator<(const char *other) const
7261     \since 4.3
7262     \overload
7263
7264     The \a other const char pointer is converted to a QString using
7265     the QString::fromAscii() function.
7266
7267     You can disable this operator by defining \c
7268     QT_NO_CAST_FROM_ASCII when you compile your applications. This
7269     can be useful if you want to ensure that all user-visible strings
7270     go through QObject::tr(), for example.
7271 */
7272
7273 /*!
7274     \fn bool QLatin1String::operator>=(const QString &other) const
7275
7276     Returns true if this string is lexically greater than or equal
7277     to string \a other; otherwise returns false.
7278
7279     The comparison is based exclusively on the numeric Unicode values
7280     of the characters and is very fast, but is not what a human would
7281     expect. Consider sorting user-interface strings with
7282     QString::localeAwareCompare().
7283 */
7284
7285 /*!
7286     \fn bool QLatin1String::operator>=(const char *other) const
7287     \since 4.3
7288     \overload
7289
7290     The \a other const char pointer is converted to a QString using
7291     the QString::fromAscii() function.
7292
7293     You can disable this operator by defining \c
7294     QT_NO_CAST_FROM_ASCII when you compile your applications. This
7295     can be useful if you want to ensure that all user-visible strings
7296     go through QObject::tr(), for example.
7297 */
7298
7299 /*! \fn bool QLatin1String::operator<=(const QString &other) const
7300
7301     Returns true if this string is lexically less than or equal
7302     to string \a other; otherwise returns false.
7303
7304     The comparison is based exclusively on the numeric Unicode values
7305     of the characters and is very fast, but is not what a human would
7306     expect. Consider sorting user-interface strings with
7307     QString::localeAwareCompare().
7308 */
7309
7310 /*!
7311     \fn bool QLatin1String::operator<=(const char *other) const
7312     \since 4.3
7313     \overload
7314
7315     The \a other const char pointer is converted to a QString using
7316     the QString::fromAscii() function.
7317
7318     You can disable this operator by defining \c
7319     QT_NO_CAST_FROM_ASCII when you compile your applications. This
7320     can be useful if you want to ensure that all user-visible strings
7321     go through QObject::tr(), for example.
7322 */
7323
7324
7325
7326 /*! \fn bool operator==(const QLatin1String &s1, const QLatin1String &s2)
7327    \relates QLatin1String
7328
7329    Returns true if string \a s1 is lexically equal to string \a s2; otherwise
7330    returns false.
7331 */
7332 /*! \fn bool operator!=(const QLatin1String &s1, const QLatin1String &s2)
7333    \relates QLatin1String
7334
7335    Returns true if string \a s1 is lexically unequal to string \a s2; otherwise
7336    returns false.
7337 */
7338 /*! \fn bool operator<(const QLatin1String &s1, const QLatin1String &s2)
7339    \relates QLatin1String
7340
7341    Returns true if string \a s1 is lexically smaller than string \a s2; otherwise
7342    returns false.
7343 */
7344 /*! \fn bool operator<=(const QLatin1String &s1, const QLatin1String &s2)
7345    \relates QLatin1String
7346
7347    Returns true if string \a s1 is lexically smaller than or equal to string \a s2; otherwise
7348    returns false.
7349 */
7350 /*! \fn bool operator>(const QLatin1String &s1, const QLatin1String &s2)
7351    \relates QLatin1String
7352
7353    Returns true if string \a s1 is lexically greater than string \a s2; otherwise
7354    returns false.
7355 */
7356 /*! \fn bool operator>=(const QLatin1String &s1, const QLatin1String &s2)
7357    \relates QLatin1String
7358
7359    Returns true if string \a s1 is lexically greater than or equal to
7360    string \a s2; otherwise returns false.
7361 */
7362
7363
7364 #if !defined(QT_NO_DATASTREAM) || (defined(QT_BOOTSTRAPPED) && !defined(QT_BUILD_QMAKE))
7365 /*!
7366     \fn QDataStream &operator<<(QDataStream &stream, const QString &string)
7367     \relates QString
7368
7369     Writes the given \a string to the specified \a stream.
7370
7371     \sa {Serializing Qt Data Types}
7372 */
7373
7374 QDataStream &operator<<(QDataStream &out, const QString &str)
7375 {
7376     if (out.version() == 1) {
7377         out << str.toLatin1();
7378     } else {
7379         if (!str.isNull() || out.version() < 3) {
7380             if ((out.byteOrder() == QDataStream::BigEndian) == (QSysInfo::ByteOrder == QSysInfo::BigEndian)) {
7381                 out.writeBytes(reinterpret_cast<const char *>(str.unicode()), sizeof(QChar) * str.length());
7382             } else {
7383                 QVarLengthArray<ushort> buffer(str.length());
7384                 const ushort *data = reinterpret_cast<const ushort *>(str.constData());
7385                 for (int i = 0; i < str.length(); i++) {
7386                     buffer[i] = qbswap(*data);
7387                     ++data;
7388                 }
7389                 out.writeBytes(reinterpret_cast<const char *>(buffer.data()), sizeof(ushort) * buffer.size());
7390             }
7391         } else {
7392             // write null marker
7393             out << (quint32)0xffffffff;
7394         }
7395     }
7396     return out;
7397 }
7398
7399 /*!
7400     \fn QDataStream &operator>>(QDataStream &stream, QString &string)
7401     \relates QString
7402
7403     Reads a string from the specified \a stream into the given \a string.
7404
7405     \sa {Serializing Qt Data Types}
7406 */
7407
7408 QDataStream &operator>>(QDataStream &in, QString &str)
7409 {
7410 #ifdef QT_QSTRING_UCS_4
7411 #if defined(Q_CC_GNU)
7412 #warning "operator>> not working properly"
7413 #endif
7414 #endif
7415
7416     if (in.version() == 1) {
7417         QByteArray l;
7418         in >> l;
7419         str = QString::fromLatin1(l);
7420     } else {
7421         quint32 bytes = 0;
7422         in >> bytes;                                  // read size of string
7423         if (bytes == 0xffffffff) {                    // null string
7424             str.clear();
7425         } else if (bytes > 0) {                       // not empty
7426             if (bytes & 0x1) {
7427                 str.clear();
7428                 in.setStatus(QDataStream::ReadCorruptData);
7429                 return in;
7430             }
7431
7432             const quint32 Step = 1024 * 1024;
7433             quint32 len = bytes / 2;
7434             quint32 allocated = 0;
7435
7436             while (allocated < len) {
7437                 int blockSize = qMin(Step, len - allocated);
7438                 str.resize(allocated + blockSize);
7439                 if (in.readRawData(reinterpret_cast<char *>(str.data()) + allocated * 2,
7440                                    blockSize * 2) != blockSize * 2) {
7441                     str.clear();
7442                     in.setStatus(QDataStream::ReadPastEnd);
7443                     return in;
7444                 }
7445                 allocated += blockSize;
7446             }
7447
7448             if ((in.byteOrder() == QDataStream::BigEndian)
7449                     != (QSysInfo::ByteOrder == QSysInfo::BigEndian)) {
7450                 ushort *data = reinterpret_cast<ushort *>(str.data());
7451                 while (len--) {
7452                     *data = qbswap(*data);
7453                     ++data;
7454                 }
7455             }
7456         } else {
7457             str = QString(QLatin1String(""));
7458         }
7459     }
7460     return in;
7461 }
7462 #endif // QT_NO_DATASTREAM
7463
7464
7465
7466
7467 /*!
7468     \class QStringRef
7469     \since 4.3
7470     \brief The QStringRef class provides a thin wrapper around QString substrings.
7471     \reentrant
7472     \ingroup tools
7473     \ingroup string-processing
7474
7475     QStringRef provides a read-only subset of the QString API.
7476
7477     A string reference explicitly references a portion of a string()
7478     with a given size(), starting at a specific position(). Calling
7479     toString() returns a copy of the data as a real QString instance.
7480
7481     This class is designed to improve the performance of substring
7482     handling when manipulating substrings obtained from existing QString
7483     instances. QStringRef avoids the memory allocation and reference
7484     counting overhead of a standard QString by simply referencing a
7485     part of the original string. This can prove to be advantageous in
7486     low level code, such as that used in a parser, at the expense of
7487     potentially more complex code.
7488
7489     For most users, there are no semantic benefits to using QStringRef
7490     instead of QString since QStringRef requires attention to be paid
7491     to memory management issues, potentially making code more complex
7492     to write and maintain.
7493
7494     \warning A QStringRef is only valid as long as the referenced
7495     string exists. If the original string is deleted, the string
7496     reference points to an invalid memory location.
7497
7498     We suggest that you only use this class in stable code where profiling
7499     has clearly identified that performance improvements can be made by
7500     replacing standard string operations with the optimized substring
7501     handling provided by this class.
7502
7503     \sa {Implicitly Shared Classes}
7504 */
7505
7506
7507 /*!
7508  \fn QStringRef::QStringRef()
7509
7510  Constructs an empty string reference.
7511 */
7512
7513 /*! \fn QStringRef::QStringRef(const QString *string, int position, int length)
7514
7515 Constructs a string reference to the range of characters in the given
7516 \a string specified by the starting \a position and \a length in characters.
7517
7518 \warning This function exists to improve performance as much as possible,
7519 and performs no bounds checking. For program correctness, \a position and
7520 \a length must describe a valid substring of \a string.
7521
7522 This means that the starting \a position must be positive or 0 and smaller
7523 than \a string's length, and \a length must be positive or 0 but smaller than
7524 the string's length minus the starting \a position;
7525 i.e, 0 <= position < string->length() and
7526 0 <= length <= string->length() - position must both be satisfied.
7527 */
7528
7529 /*! \fn QStringRef::QStringRef(const QString *string)
7530
7531 Constructs a string reference to the given \a string.
7532 */
7533
7534 /*! \fn QStringRef::QStringRef(const QStringRef &other)
7535
7536 Constructs a copy of the \a other string reference.
7537  */
7538 /*!
7539 \fn QStringRef::~QStringRef()
7540
7541 Destroys the string reference.
7542
7543 Since this class is only used to refer to string data, and does not take
7544 ownership of it, no memory is freed when instances are destroyed.
7545 */
7546
7547
7548 /*!
7549     \fn int QStringRef::position() const
7550
7551     Returns the starting position in the referenced string that is referred to
7552     by the string reference.
7553
7554     \sa size(), string()
7555 */
7556
7557 /*!
7558     \fn int QStringRef::size() const
7559
7560     Returns the number of characters referred to by the string reference.
7561     Equivalent to length() and count().
7562
7563     \sa position(), string()
7564 */
7565 /*!
7566     \fn int QStringRef::count() const
7567     Returns the number of characters referred to by the string reference.
7568     Equivalent to size() and length().
7569
7570     \sa position(), string()
7571 */
7572 /*!
7573     \fn int QStringRef::length() const
7574     Returns the number of characters referred to by the string reference.
7575     Equivalent to size() and count().
7576
7577     \sa position(), string()
7578 */
7579
7580
7581 /*!
7582     \fn bool QStringRef::isEmpty() const
7583
7584     Returns true if the string reference has no characters; otherwise returns
7585     false.
7586
7587     A string reference is empty if its size is zero.
7588
7589     \sa size()
7590 */
7591
7592 /*!
7593     \fn bool QStringRef::isNull() const
7594
7595     Returns true if string() returns a null pointer or a pointer to a
7596     null string; otherwise returns true.
7597
7598     \sa size()
7599 */
7600
7601 /*!
7602     \fn const QString *QStringRef::string() const
7603
7604     Returns a pointer to the string referred to by the string reference, or
7605     0 if it does not reference a string.
7606
7607     \sa unicode()
7608 */
7609
7610
7611 /*!
7612     \fn const QChar *QStringRef::unicode() const
7613
7614     Returns a Unicode representation of the string reference. Since
7615     the data stems directly from the referenced string, it is not
7616     null-terminated unless the string reference includes the string's
7617     null terminator.
7618
7619     \sa string()
7620 */
7621
7622 /*!
7623     \fn const QChar *QStringRef::data() const
7624
7625     Same as unicode().
7626 */
7627
7628 /*!
7629     \fn const QChar *QStringRef::constData() const
7630
7631     Same as unicode().
7632 */
7633
7634 /*!
7635     Returns a copy of the string reference as a QString object.
7636
7637     If the string reference is not a complete reference of the string
7638     (meaning that position() is 0 and size() equals string()->size()),
7639     this function will allocate a new string to return.
7640
7641     \sa string()
7642 */
7643
7644 QString QStringRef::toString() const {
7645     if (!m_string)
7646         return QString();
7647     if (m_size && m_position == 0 && m_size == m_string->size())
7648         return *m_string;
7649     return QString(m_string->unicode() + m_position, m_size);
7650 }
7651
7652
7653 /*! \relates QStringRef
7654
7655    Returns true if string reference \a s1 is lexically equal to string reference \a s2; otherwise
7656    returns false.
7657 */
7658 bool operator==(const QStringRef &s1,const QStringRef &s2)
7659 { return (s1.size() == s2.size() &&
7660           qMemEquals((const ushort *)s1.unicode(), (const ushort *)s2.unicode(), s1.size()));
7661 }
7662
7663 /*! \relates QStringRef
7664
7665    Returns true if string \a s1 is lexically equal to string reference \a s2; otherwise
7666    returns false.
7667 */
7668 bool operator==(const QString &s1,const QStringRef &s2)
7669 { return (s1.size() == s2.size() &&
7670           qMemEquals((const ushort *)s1.unicode(), (const ushort *)s2.unicode(), s1.size()));
7671 }
7672
7673 /*! \relates QStringRef
7674
7675    Returns true if string  \a s1 is lexically equal to string reference \a s2; otherwise
7676    returns false.
7677 */
7678 bool operator==(const QLatin1String &s1, const QStringRef &s2)
7679 {
7680     if (s1.size() != s2.size())
7681         return false;
7682
7683     const ushort *uc = reinterpret_cast<const ushort *>(s2.unicode());
7684     const ushort *e = uc + s2.size();
7685     const uchar *c = reinterpret_cast<const uchar *>(s1.latin1());
7686     if (!c)
7687         return s2.isEmpty();
7688
7689     while (*c) {
7690         if (uc == e || *uc != *c)
7691             return false;
7692         ++uc;
7693         ++c;
7694     }
7695     return (uc == e);
7696 }
7697
7698 /*!
7699    \relates QStringRef
7700
7701     Returns true if string reference \a s1 is lexically less than
7702     string reference \a s2; otherwise returns false.
7703
7704     The comparison is based exclusively on the numeric Unicode values
7705     of the characters and is very fast, but is not what a human would
7706     expect. Consider sorting user-interface strings using the
7707     QString::localeAwareCompare() function.
7708 */
7709 bool operator<(const QStringRef &s1,const QStringRef &s2)
7710 {
7711     return ucstrcmp(s1.constData(), s1.length(), s2.constData(), s2.length()) < 0;
7712 }
7713
7714 /*!\fn bool operator<=(const QStringRef &s1,const QStringRef &s2)
7715
7716    \relates QStringRef
7717
7718     Returns true if string reference \a s1 is lexically less than
7719     or equal to string reference \a s2; otherwise returns false.
7720
7721     The comparison is based exclusively on the numeric Unicode values
7722     of the characters and is very fast, but is not what a human would
7723     expect. Consider sorting user-interface strings using the
7724     QString::localeAwareCompare() function.
7725 */
7726
7727 /*!\fn bool operator>=(const QStringRef &s1,const QStringRef &s2)
7728
7729    \relates QStringRef
7730
7731     Returns true if string reference \a s1 is lexically greater than
7732     or equal to string reference \a s2; otherwise returns false.
7733
7734     The comparison is based exclusively on the numeric Unicode values
7735     of the characters and is very fast, but is not what a human would
7736     expect. Consider sorting user-interface strings using the
7737     QString::localeAwareCompare() function.
7738 */
7739
7740 /*!\fn bool operator>(const QStringRef &s1,const QStringRef &s2)
7741
7742    \relates QStringRef
7743
7744     Returns true if string reference \a s1 is lexically greater than
7745     string reference \a s2; otherwise returns false.
7746
7747     The comparison is based exclusively on the numeric Unicode values
7748     of the characters and is very fast, but is not what a human would
7749     expect. Consider sorting user-interface strings using the
7750     QString::localeAwareCompare() function.
7751 */
7752
7753
7754 /*!
7755     \fn const QChar QStringRef::at(int position) const
7756
7757     Returns the character at the given index \a position in the
7758     string reference.
7759
7760     The \a position must be a valid index position in the string
7761     (i.e., 0 <= \a position < size()).
7762 */
7763
7764 /*!
7765     \fn void QStringRef::clear()
7766
7767     Clears the contents of the string reference by making it null and empty.
7768
7769     \sa isEmpty(), isNull()
7770 */
7771
7772 /*!
7773     \fn QStringRef &QStringRef::operator=(const QStringRef &other)
7774
7775     Assigns the \a other string reference to this string reference, and
7776     returns the result.
7777 */
7778
7779 /*!
7780     \fn QStringRef &QStringRef::operator=(const QString *string)
7781
7782     Constructs a string reference to the given \a string and assigns it to
7783     this string reference, returning the result.
7784 */
7785
7786 /*!
7787     \typedef QString::DataPtr
7788     \internal
7789 */
7790
7791 /*!
7792     \fn DataPtr & QString::data_ptr()
7793     \internal
7794 */
7795
7796
7797
7798 /*!  Appends the string reference to \a string, and returns a new
7799 reference to the combined string data.
7800  */
7801 QStringRef QStringRef::appendTo(QString *string) const
7802 {
7803     if (!string)
7804         return QStringRef();
7805     int pos = string->size();
7806     string->insert(pos, unicode(), size());
7807     return QStringRef(string, pos, size());
7808 }
7809
7810 /*!
7811     \fn int QStringRef::compare(const QStringRef &s1, const QString &s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
7812     \since 4.5
7813
7814     Compares the string \a s1 with the string \a s2 and returns an
7815     integer less than, equal to, or greater than zero if \a s1
7816     is less than, equal to, or greater than \a s2.
7817
7818     If \a cs is Qt::CaseSensitive, the comparison is case sensitive;
7819     otherwise the comparison is case insensitive.
7820 */
7821
7822 /*!
7823     \fn int QStringRef::compare(const QStringRef &s1, const QStringRef &s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
7824     \since 4.5
7825     \overload
7826
7827     Compares the string \a s1 with the string \a s2 and returns an
7828     integer less than, equal to, or greater than zero if \a s1
7829     is less than, equal to, or greater than \a s2.
7830
7831     If \a cs is Qt::CaseSensitive, the comparison is case sensitive;
7832     otherwise the comparison is case insensitive.
7833 */
7834
7835 /*!
7836     \fn int QStringRef::compare(const QStringRef &s1, QLatin1String s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
7837     \since 4.5
7838     \overload
7839
7840     Compares the string \a s1 with the string \a s2 and returns an
7841     integer less than, equal to, or greater than zero if \a s1
7842     is less than, equal to, or greater than \a s2.
7843
7844     If \a cs is Qt::CaseSensitive, the comparison is case sensitive;
7845     otherwise the comparison is case insensitive.
7846 */
7847
7848 /*!
7849     \overload
7850     \fn int QStringRef::compare(const QString &other, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
7851     \since 4.5
7852
7853     Compares this string with the \a other string and returns an
7854     integer less than, equal to, or greater than zero if this string
7855     is less than, equal to, or greater than the \a other string.
7856
7857     If \a cs is Qt::CaseSensitive, the comparison is case sensitive;
7858     otherwise the comparison is case insensitive.
7859
7860     Equivalent to \c {compare(*this, other, cs)}.
7861
7862     \sa QString::compare()
7863 */
7864
7865 /*!
7866     \overload
7867     \fn int QStringRef::compare(const QStringRef &other, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
7868     \since 4.5
7869
7870     Compares this string with the \a other string and returns an
7871     integer less than, equal to, or greater than zero if this string
7872     is less than, equal to, or greater than the \a other string.
7873
7874     If \a cs is Qt::CaseSensitive, the comparison is case sensitive;
7875     otherwise the comparison is case insensitive.
7876
7877     Equivalent to \c {compare(*this, other, cs)}.
7878
7879     \sa QString::compare()
7880 */
7881
7882 /*!
7883     \overload
7884     \fn int QStringRef::compare(QLatin1String other, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
7885     \since 4.5
7886
7887     Compares this string with the \a other string and returns an
7888     integer less than, equal to, or greater than zero if this string
7889     is less than, equal to, or greater than the \a other string.
7890
7891     If \a cs is Qt::CaseSensitive, the comparison is case sensitive;
7892     otherwise the comparison is case insensitive.
7893
7894     Equivalent to \c {compare(*this, other, cs)}.
7895
7896     \sa QString::compare()
7897 */
7898
7899 /*!
7900     \fn int QStringRef::localeAwareCompare(const QStringRef &s1, const QString & s2)
7901     \since 4.5
7902
7903     Compares \a s1 with \a s2 and returns an integer less than, equal
7904     to, or greater than zero if \a s1 is less than, equal to, or
7905     greater than \a s2.
7906
7907     The comparison is performed in a locale- and also
7908     platform-dependent manner. Use this function to present sorted
7909     lists of strings to the user.
7910
7911     On Mac OS X, this function compares according the
7912     "Order for sorted lists" setting in the International prefereces panel.
7913
7914     \sa compare(), QTextCodec::locale()
7915 */
7916
7917 /*!
7918     \fn int QStringRef::localeAwareCompare(const QStringRef &s1, const QStringRef & s2)
7919     \since 4.5
7920     \overload
7921
7922     Compares \a s1 with \a s2 and returns an integer less than, equal
7923     to, or greater than zero if \a s1 is less than, equal to, or
7924     greater than \a s2.
7925
7926     The comparison is performed in a locale- and also
7927     platform-dependent manner. Use this function to present sorted
7928     lists of strings to the user.
7929
7930 */
7931
7932 /*!
7933     \fn int QStringRef::localeAwareCompare(const QString &other) const
7934     \since 4.5
7935     \overload
7936
7937     Compares this string with the \a other string and returns an
7938     integer less than, equal to, or greater than zero if this string
7939     is less than, equal to, or greater than the \a other string.
7940
7941     The comparison is performed in a locale- and also
7942     platform-dependent manner. Use this function to present sorted
7943     lists of strings to the user.
7944 */
7945
7946 /*!
7947     \fn int QStringRef::localeAwareCompare(const QStringRef &other) const
7948     \since 4.5
7949     \overload
7950
7951     Compares this string with the \a other string and returns an
7952     integer less than, equal to, or greater than zero if this string
7953     is less than, equal to, or greater than the \a other string.
7954
7955     The comparison is performed in a locale- and also
7956     platform-dependent manner. Use this function to present sorted
7957     lists of strings to the user.
7958 */
7959
7960 /*!
7961     \fn QString &QString::append(const QStringRef &reference)
7962     \since 4.4
7963
7964     Appends the given string \a reference to this string and returns the result.
7965  */
7966 QString &QString::append(const QStringRef &str)
7967 {
7968     if (str.string() == this) {
7969         str.appendTo(this);
7970     } else if (str.string()) {
7971         int oldSize = size();
7972         resize(oldSize + str.size());
7973         memcpy(data() + oldSize, str.unicode(), str.size() * sizeof(QChar));
7974     }
7975     return *this;
7976 }
7977
7978 /*!
7979     \since 4.4
7980
7981     Returns a substring reference to the \a n leftmost characters
7982     of the string.
7983
7984     If \a n is greater than size() or less than zero, a reference to the entire
7985     string is returned.
7986
7987     \snippet doc/src/snippets/qstring/main.cpp leftRef
7988
7989     \sa left(), rightRef(), midRef(), startsWith()
7990 */
7991 QStringRef QString::leftRef(int n)  const
7992 {
7993     if (n >= d->size || n < 0)
7994         n = d->size;
7995     return QStringRef(this, 0, n);
7996 }
7997
7998 /*!
7999     \since 4.4
8000
8001     Returns a substring reference to the \a n rightmost characters
8002     of the string.
8003
8004     If \a n is greater than size() or less than zero, a reference to the entire
8005     string is returned.
8006
8007     \snippet doc/src/snippets/qstring/main.cpp rightRef
8008
8009     \sa right(), leftRef(), midRef(), endsWith()
8010 */
8011 QStringRef QString::rightRef(int n) const
8012 {
8013     if (n >= d->size || n < 0)
8014         n = d->size;
8015     return QStringRef(this, d->size - n, n);
8016 }
8017
8018 /*!
8019     \since 4.4
8020
8021     Returns a substring reference to \a n characters of this string,
8022     starting at the specified \a position.
8023
8024     If the \a position exceeds the length of the string, a null
8025     reference is returned.
8026
8027     If there are less than \a n characters available in the string,
8028     starting at the given \a position, or if \a n is -1 (default), the
8029     function returns all characters from the specified \a position
8030     onwards.
8031
8032     Example:
8033
8034     \snippet doc/src/snippets/qstring/main.cpp midRef
8035
8036     \sa mid(), leftRef(), rightRef()
8037 */
8038
8039 QStringRef QString::midRef(int position, int n) const
8040 {
8041     if (position > d->size)
8042         return QStringRef();
8043     if (position < 0)
8044         position = 0;
8045     if (n < 0 || n > d->size - position)
8046         n = d->size - position;
8047     return QStringRef(this, position, n);
8048 }
8049
8050 /*!
8051   \since 4.8
8052
8053   Returns the index position of the first occurrence of the string \a
8054   str in this string reference, searching forward from index position
8055   \a from. Returns -1 if \a str is not found.
8056
8057   If \a cs is Qt::CaseSensitive (default), the search is case
8058   sensitive; otherwise the search is case insensitive.
8059
8060   If \a from is -1, the search starts at the last character; if it is
8061   -2, at the next to last character and so on.
8062
8063   \sa QString::indexOf(), lastIndexOf(), contains(), count()
8064 */
8065 int QStringRef::indexOf(const QString &str, int from, Qt::CaseSensitivity cs) const
8066 {
8067     return qFindString(unicode(), length(), from, str.unicode(), str.length(), cs);
8068 }
8069
8070 /*!
8071     \since 4.8
8072     \overload indexOf()
8073
8074     Returns the index position of the first occurrence of the
8075     character \a ch in the string reference, searching forward from
8076     index position \a from. Returns -1 if \a ch could not be found.
8077
8078     \sa QString::indexOf(), lastIndexOf(), contains(), count()
8079 */
8080 int QStringRef::indexOf(QChar ch, int from, Qt::CaseSensitivity cs) const
8081 {
8082     return findChar(unicode(), length(), ch, from, cs);
8083 }
8084
8085 /*!
8086   \since 4.8
8087
8088   Returns the index position of the first occurrence of the string \a
8089   str in this string reference, searching forward from index position
8090   \a from. Returns -1 if \a str is not found.
8091
8092   If \a cs is Qt::CaseSensitive (default), the search is case
8093   sensitive; otherwise the search is case insensitive.
8094
8095   If \a from is -1, the search starts at the last character; if it is
8096   -2, at the next to last character and so on.
8097
8098   \sa QString::indexOf(), lastIndexOf(), contains(), count()
8099 */
8100 int QStringRef::indexOf(QLatin1String str, int from, Qt::CaseSensitivity cs) const
8101 {
8102     return qt_find_latin1_string(unicode(), size(), str, from, cs);
8103 }
8104
8105 /*!
8106     \since 4.8
8107
8108     \overload indexOf()
8109
8110     Returns the index position of the first occurrence of the string
8111     reference \a str in this string reference, searching forward from
8112     index position \a from. Returns -1 if \a str is not found.
8113
8114     If \a cs is Qt::CaseSensitive (default), the search is case
8115     sensitive; otherwise the search is case insensitive.
8116
8117     \sa QString::indexOf(), lastIndexOf(), contains(), count()
8118 */
8119 int QStringRef::indexOf(const QStringRef &str, int from, Qt::CaseSensitivity cs) const
8120 {
8121     return qFindString(unicode(), size(), from, str.unicode(), str.size(), cs);
8122 }
8123
8124 /*!
8125   \since 4.8
8126
8127   Returns the index position of the last occurrence of the string \a
8128   str in this string reference, searching backward from index position
8129   \a from. If \a from is -1 (default), the search starts at the last
8130   character; if \a from is -2, at the next to last character and so
8131   on. Returns -1 if \a str is not found.
8132
8133   If \a cs is Qt::CaseSensitive (default), the search is case
8134   sensitive; otherwise the search is case insensitive.
8135
8136   \sa QString::lastIndexOf(), indexOf(), contains(), count()
8137 */
8138 int QStringRef::lastIndexOf(const QString &str, int from, Qt::CaseSensitivity cs) const
8139 {
8140     const int sl = str.size();
8141     if (sl == 1)
8142         return lastIndexOf(str.at(0), from, cs);
8143
8144     const int l = size();;
8145     if (from < 0)
8146         from += l;
8147     int delta = l - sl;
8148     if (from == l && sl == 0)
8149         return from;
8150     if (from < 0 || from >= l || delta < 0)
8151         return -1;
8152     if (from > delta)
8153         from = delta;
8154
8155     return lastIndexOfHelper(reinterpret_cast<const ushort*>(unicode()), from,
8156                              reinterpret_cast<const ushort*>(str.unicode()), str.size(), cs);
8157 }
8158
8159 /*!
8160   \since 4.8
8161   \overload lastIndexOf()
8162
8163   Returns the index position of the last occurrence of the character
8164   \a ch, searching backward from position \a from.
8165
8166   \sa QString::lastIndexOf(), indexOf(), contains(), count()
8167 */
8168 int QStringRef::lastIndexOf(QChar ch, int from, Qt::CaseSensitivity cs) const
8169 {
8170     return qt_last_index_of(unicode(), size(), ch, from, cs);
8171 }
8172
8173 /*!
8174   \since 4.8
8175   \overload lastIndexOf()
8176
8177   Returns the index position of the last occurrence of the string \a
8178   str in this string reference, searching backward from index position
8179   \a from. If \a from is -1 (default), the search starts at the last
8180   character; if \a from is -2, at the next to last character and so
8181   on. Returns -1 if \a str is not found.
8182
8183   If \a cs is Qt::CaseSensitive (default), the search is case
8184   sensitive; otherwise the search is case insensitive.
8185
8186   \sa QString::lastIndexOf(), indexOf(), contains(), count()
8187 */
8188 int QStringRef::lastIndexOf(QLatin1String str, int from, Qt::CaseSensitivity cs) const
8189 {
8190     const int sl = str.size();
8191     if (sl == 1)
8192         return lastIndexOf(QLatin1Char(str.latin1()[0]), from, cs);
8193
8194     const int l = size();
8195     if (from < 0)
8196         from += l;
8197     int delta = l - sl;
8198     if (from == l && sl == 0)
8199         return from;
8200     if (from < 0 || from >= l || delta < 0)
8201         return -1;
8202     if (from > delta)
8203         from = delta;
8204
8205     QVarLengthArray<ushort> s(sl);
8206     for (int i = 0; i < sl; ++i)
8207         s[i] = str.latin1()[i];
8208
8209     return lastIndexOfHelper(reinterpret_cast<const ushort*>(unicode()), from, s.data(), sl, cs);
8210 }
8211
8212 /*!
8213   \since 4.8
8214   \overload lastIndexOf()
8215
8216   Returns the index position of the last occurrence of the string
8217   reference \a str in this string reference, searching backward from
8218   index position \a from. If \a from is -1 (default), the search
8219   starts at the last character; if \a from is -2, at the next to last
8220   character and so on. Returns -1 if \a str is not found.
8221
8222   If \a cs is Qt::CaseSensitive (default), the search is case
8223   sensitive; otherwise the search is case insensitive.
8224
8225   \sa QString::lastIndexOf(), indexOf(), contains(), count()
8226 */
8227 int QStringRef::lastIndexOf(const QStringRef &str, int from, Qt::CaseSensitivity cs) const
8228 {
8229     const int sl = str.size();
8230     if (sl == 1)
8231         return lastIndexOf(str.at(0), from, cs);
8232
8233     const int l = size();
8234     if (from < 0)
8235         from += l;
8236     int delta = l - sl;
8237     if (from == l && sl == 0)
8238         return from;
8239     if (from < 0 || from >= l || delta < 0)
8240         return -1;
8241     if (from > delta)
8242         from = delta;
8243
8244     return lastIndexOfHelper(reinterpret_cast<const ushort*>(unicode()), from,
8245                              reinterpret_cast<const ushort*>(str.unicode()),
8246                              str.size(), cs);
8247 }
8248
8249 /*!
8250     \since 4.8
8251     Returns the number of (potentially overlapping) occurrences of
8252     the string \a str in this string reference.
8253
8254     If \a cs is Qt::CaseSensitive (default), the search is
8255     case sensitive; otherwise the search is case insensitive.
8256
8257     \sa QString::count(), contains(), indexOf()
8258 */
8259 int QStringRef::count(const QString &str, Qt::CaseSensitivity cs) const
8260 {
8261     return qt_string_count(unicode(), size(), str.unicode(), str.size(), cs);
8262 }
8263
8264 /*!
8265     \since 4.8
8266     \overload count()
8267
8268     Returns the number of occurrences of the character \a ch in the
8269     string reference.
8270
8271     If \a cs is Qt::CaseSensitive (default), the search is
8272     case sensitive; otherwise the search is case insensitive.
8273
8274     \sa QString::count(), contains(), indexOf()
8275 */
8276 int QStringRef::count(QChar ch, Qt::CaseSensitivity cs) const
8277 {
8278     return qt_string_count(unicode(), size(), ch, cs);
8279 }
8280
8281 /*!
8282     \since 4.8
8283     \overload count()
8284
8285     Returns the number of (potentially overlapping) occurrences of the
8286     string reference \a str in this string reference.
8287
8288     If \a cs is Qt::CaseSensitive (default), the search is
8289     case sensitive; otherwise the search is case insensitive.
8290
8291     \sa QString::count(), contains(), indexOf()
8292 */
8293 int QStringRef::count(const QStringRef &str, Qt::CaseSensitivity cs) const
8294 {
8295     return qt_string_count(unicode(), size(), str.unicode(), str.size(), cs);
8296 }
8297
8298 /*!
8299     \since 4.8
8300
8301     Returns true if the string reference starts with \a str; otherwise
8302     returns false.
8303
8304     If \a cs is Qt::CaseSensitive (default), the search is
8305     case sensitive; otherwise the search is case insensitive.
8306
8307     \sa QString::startsWith(), endsWith()
8308 */
8309 bool QStringRef::startsWith(const QString &str, Qt::CaseSensitivity cs) const
8310 {
8311     return qt_starts_with(isNull() ? 0 : unicode(), size(),
8312                           str.isNull() ? 0 : str.unicode(), str.size(), cs);
8313 }
8314
8315 /*!
8316     \since 4.8
8317     \overload startsWith()
8318     \sa QString::startsWith(), endsWith()
8319 */
8320 bool QStringRef::startsWith(QLatin1String str, Qt::CaseSensitivity cs) const
8321 {
8322     return qt_starts_with(isNull() ? 0 : unicode(), size(), str, cs);
8323 }
8324
8325 /*!
8326     \since 4.8
8327     \overload startsWith()
8328     \sa QString::startsWith(), endsWith()
8329 */
8330 bool QStringRef::startsWith(const QStringRef &str, Qt::CaseSensitivity cs) const
8331 {
8332     return qt_starts_with(isNull() ? 0 : unicode(), size(),
8333                           str.isNull() ? 0 : str.unicode(), str.size(), cs);
8334 }
8335
8336 /*!
8337     \since 4.8
8338     \overload startsWith()
8339
8340     Returns true if the string reference starts with \a ch; otherwise
8341     returns false.
8342
8343     If \a cs is Qt::CaseSensitive (default), the search is case
8344     sensitive; otherwise the search is case insensitive.
8345
8346     \sa QString::startsWith(), endsWith()
8347 */
8348 bool QStringRef::startsWith(QChar ch, Qt::CaseSensitivity cs) const
8349 {
8350     if (!isEmpty()) {
8351         const ushort *data = reinterpret_cast<const ushort*>(unicode());
8352         return (cs == Qt::CaseSensitive
8353                 ? data[0] == ch
8354                 : foldCase(data[0]) == foldCase(ch.unicode()));
8355     } else {
8356         return false;
8357     }
8358 }
8359
8360 /*!
8361     \since 4.8
8362     Returns true if the string reference ends with \a str; otherwise
8363     returns false.
8364
8365     If \a cs is Qt::CaseSensitive (default), the search is case
8366     sensitive; otherwise the search is case insensitive.
8367
8368     \sa QString::endsWith(), startsWith()
8369 */
8370 bool QStringRef::endsWith(const QString &str, Qt::CaseSensitivity cs) const
8371 {
8372     return qt_ends_with(isNull() ? 0 : unicode(), size(),
8373                         str.isNull() ? 0 : str.unicode(), str.size(), cs);
8374 }
8375
8376 /*!
8377     \since 4.8
8378     \overload endsWith()
8379
8380     Returns true if the string reference ends with \a ch; otherwise
8381     returns false.
8382
8383     If \a cs is Qt::CaseSensitive (default), the search is case
8384     sensitive; otherwise the search is case insensitive.
8385
8386     \sa QString::endsWith(), endsWith()
8387 */
8388 bool QStringRef::endsWith(QChar ch, Qt::CaseSensitivity cs) const
8389 {
8390     if (!isEmpty()) {
8391         const ushort *data = reinterpret_cast<const ushort*>(unicode());
8392         const int size = length();
8393         return (cs == Qt::CaseSensitive
8394                 ? data[size - 1] == ch
8395                 : foldCase(data[size - 1]) == foldCase(ch.unicode()));
8396     } else {
8397         return false;
8398     }
8399 }
8400
8401 /*!
8402     \since 4.8
8403     \overload endsWith()
8404     \sa QString::endsWith(), endsWith()
8405 */
8406 bool QStringRef::endsWith(QLatin1String str, Qt::CaseSensitivity cs) const
8407 {
8408     return qt_ends_with(isNull() ? 0 : unicode(), size(), str, cs);
8409 }
8410
8411 /*!
8412     \since 4.8
8413     \overload endsWith()
8414     \sa QString::endsWith(), endsWith()
8415 */
8416 bool QStringRef::endsWith(const QStringRef &str, Qt::CaseSensitivity cs) const
8417 {
8418     return qt_ends_with(isNull() ? 0 : unicode(), size(),
8419                         str.isNull() ? 0 : str.unicode(), str.size(), cs);
8420 }
8421
8422
8423 /*! \fn bool QStringRef::contains(const QString &str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
8424
8425     \since 4.8
8426     Returns true if this string reference contains an occurrence of
8427     the string \a str; otherwise returns false.
8428
8429     If \a cs is Qt::CaseSensitive (default), the search is
8430     case sensitive; otherwise the search is case insensitive.
8431
8432     \sa indexOf(), count()
8433 */
8434
8435 /*! \fn bool QStringRef::contains(QChar ch, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
8436
8437     \overload contains()
8438     \since 4.8
8439
8440     Returns true if this string contains an occurrence of the
8441     character \a ch; otherwise returns false.
8442
8443     If \a cs is Qt::CaseSensitive (default), the search is
8444     case sensitive; otherwise the search is case insensitive.
8445
8446 */
8447
8448 /*! \fn bool QStringRef::contains(const QStringRef &str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
8449     \overload contains()
8450     \since 4.8
8451
8452     Returns true if this string reference contains an occurrence of
8453     the string reference \a str; otherwise returns false.
8454
8455     If \a cs is Qt::CaseSensitive (default), the search is
8456     case sensitive; otherwise the search is case insensitive.
8457
8458     \sa indexOf(), count()
8459 */
8460
8461 /*! \fn bool QStringRef::contains(QLatin1String str, Qt::CaseSensitivity cs) const
8462     \since 4,8
8463     \overload contains()
8464
8465     Returns true if this string reference contains an occurrence of
8466     the string \a str; otherwise returns false.
8467
8468     If \a cs is Qt::CaseSensitive (default), the search is
8469     case sensitive; otherwise the search is case insensitive.
8470
8471     \sa indexOf(), count()
8472 */
8473
8474 static inline int qt_last_index_of(const QChar *haystack, int haystackLen, QChar needle,
8475                                    int from, Qt::CaseSensitivity cs)
8476 {
8477     ushort c = needle.unicode();
8478     if (from < 0)
8479         from += haystackLen;
8480     if (from < 0 || from >= haystackLen)
8481         return -1;
8482     if (from >= 0) {
8483         const ushort *b = reinterpret_cast<const ushort*>(haystack);
8484         const ushort *n = b + from;
8485         if (cs == Qt::CaseSensitive) {
8486             for (; n >= b; --n)
8487                 if (*n == c)
8488                     return n - b;
8489         } else {
8490             c = foldCase(c);
8491             for (; n >= b; --n)
8492                 if (foldCase(*n) == c)
8493                     return n - b;
8494         }
8495     }
8496     return -1;
8497
8498
8499 }
8500
8501 static inline int qt_string_count(const QChar *haystack, int haystackLen,
8502                                   const QChar *needle, int needleLen,
8503                                   Qt::CaseSensitivity cs)
8504 {
8505     int num = 0;
8506     int i = -1;
8507     if (haystackLen > 500 && needleLen > 5) {
8508         QStringMatcher matcher(needle, needleLen, cs);
8509         while ((i = matcher.indexIn(haystack, haystackLen, i + 1)) != -1)
8510             ++num;
8511     } else {
8512         while ((i = qFindString(haystack, haystackLen, i + 1, needle, needleLen, cs)) != -1)
8513             ++num;
8514     }
8515     return num;
8516 }
8517
8518 static inline int qt_string_count(const QChar *unicode, int size, QChar ch,
8519                                   Qt::CaseSensitivity cs)
8520 {
8521     ushort c = ch.unicode();
8522     int num = 0;
8523     const ushort *b = reinterpret_cast<const ushort*>(unicode);
8524     const ushort *i = b + size;
8525     if (cs == Qt::CaseSensitive) {
8526         while (i != b)
8527             if (*--i == c)
8528                 ++num;
8529     } else {
8530         c = foldCase(c);
8531         while (i != b)
8532             if (foldCase(*(--i)) == c)
8533                 ++num;
8534     }
8535     return num;
8536 }
8537
8538 static inline int qt_find_latin1_string(const QChar *haystack, int size,
8539                                         const QLatin1String &needle,
8540                                         int from, Qt::CaseSensitivity cs)
8541 {
8542     const char *latin1 = needle.latin1();
8543     int len = needle.size();
8544     QVarLengthArray<ushort> s(len);
8545     for (int i = 0; i < len; ++i)
8546         s[i] = latin1[i];
8547
8548     return qFindString(haystack, size, from,
8549                        reinterpret_cast<const QChar*>(s.constData()), len, cs);
8550 }
8551
8552 static inline bool qt_starts_with(const QChar *haystack, int haystackLen,
8553                                   const QChar *needle, int needleLen, Qt::CaseSensitivity cs)
8554 {
8555     if (!haystack)
8556         return !needle;
8557     if (haystackLen == 0)
8558         return needleLen == 0;
8559     if (needleLen > haystackLen)
8560         return false;
8561
8562     const ushort *h = reinterpret_cast<const ushort*>(haystack);
8563     const ushort *n = reinterpret_cast<const ushort*>(needle);
8564
8565     if (cs == Qt::CaseSensitive) {
8566         return qMemEquals(h, n, needleLen);
8567     } else {
8568         uint last = 0;
8569         uint olast = 0;
8570         for (int i = 0; i < needleLen; ++i)
8571             if (foldCase(h[i], last) != foldCase(n[i], olast))
8572                 return false;
8573     }
8574     return true;
8575 }
8576
8577 static inline bool qt_starts_with(const QChar *haystack, int haystackLen,
8578                                   const QLatin1String &needle, Qt::CaseSensitivity cs)
8579 {
8580     if (!haystack)
8581         return !needle.latin1();
8582     if (haystackLen == 0)
8583         return !needle.latin1() || *needle.latin1() == 0;
8584     const int slen = needle.size();
8585     if (slen > haystackLen)
8586         return false;
8587     const ushort *data = reinterpret_cast<const ushort*>(haystack);
8588     const uchar *latin = reinterpret_cast<const uchar*>(needle.latin1());
8589     if (cs == Qt::CaseSensitive) {
8590         for (int i = 0; i < slen; ++i)
8591             if (data[i] != latin[i])
8592                 return false;
8593     } else {
8594         for (int i = 0; i < slen; ++i)
8595             if (foldCase(data[i]) != foldCase((ushort)latin[i]))
8596                 return false;
8597     }
8598     return true;
8599 }
8600
8601 static inline bool qt_ends_with(const QChar *haystack, int haystackLen,
8602                                 const QChar *needle, int needleLen, Qt::CaseSensitivity cs)
8603 {
8604     if (!haystack)
8605         return !needle;
8606     if (haystackLen == 0)
8607         return needleLen == 0;
8608     const int pos = haystackLen - needleLen;
8609     if (pos < 0)
8610         return false;
8611
8612     const ushort *h = reinterpret_cast<const ushort*>(haystack);
8613     const ushort *n = reinterpret_cast<const ushort*>(needle);
8614
8615     if (cs == Qt::CaseSensitive) {
8616         return qMemEquals(h + pos, n, needleLen);
8617     } else {
8618         uint last = 0;
8619         uint olast = 0;
8620         for (int i = 0; i < needleLen; i++)
8621             if (foldCase(h[pos+i], last) != foldCase(n[i], olast))
8622                 return false;
8623     }
8624     return true;
8625 }
8626
8627
8628 static inline bool qt_ends_with(const QChar *haystack, int haystackLen,
8629                                 const QLatin1String &needle, Qt::CaseSensitivity cs)
8630 {
8631     if (!haystack)
8632         return !needle.latin1();
8633     if (haystackLen == 0)
8634         return !needle.latin1() || *needle.latin1() == 0;
8635     const int slen = needle.size();
8636     int pos = haystackLen - slen;
8637     if (pos < 0)
8638         return false;
8639     const uchar *latin = reinterpret_cast<const uchar*>(needle.latin1());
8640     const ushort *data = reinterpret_cast<const ushort*>(haystack);
8641     if (cs == Qt::CaseSensitive) {
8642         for (int i = 0; i < slen; i++)
8643             if (data[pos+i] != latin[i])
8644                 return false;
8645     } else {
8646         for (int i = 0; i < slen; i++)
8647             if (foldCase(data[pos+i]) != foldCase((ushort)latin[i]))
8648                 return false;
8649     }
8650     return true;
8651 }
8652
8653 /*!
8654     \since 4.8
8655
8656     Returns a Latin-1 representation of the string as a QByteArray.
8657
8658     The returned byte array is undefined if the string contains non-Latin1
8659     characters. Those characters may be suppressed or replaced with a
8660     question mark.
8661
8662     \sa toAscii(), toUtf8(), toLocal8Bit(), QTextCodec
8663 */
8664 QByteArray QStringRef::toLatin1() const
8665 {
8666     return toLatin1_helper(unicode(), length());
8667 }
8668
8669 /*!
8670     \since 4.8
8671
8672     Returns an 8-bit representation of the string as a QByteArray.
8673
8674     If a codec has been set using QTextCodec::setCodecForCStrings(),
8675     it is used to convert Unicode to 8-bit char; otherwise this
8676     function does the same as toLatin1().
8677
8678     Note that, despite the name, this function does not necessarily return an US-ASCII
8679     (ANSI X3.4-1986) string and its result may not be US-ASCII compatible.
8680
8681     \sa toLatin1(), toUtf8(), toLocal8Bit(), QTextCodec
8682 */
8683 QByteArray QStringRef::toAscii() const
8684 {
8685 #ifndef QT_NO_TEXTCODEC
8686     if (QString::codecForCStrings)
8687         return QString::codecForCStrings->fromUnicode(unicode(), length());
8688 #endif // QT_NO_TEXTCODEC
8689     return toLatin1();
8690 }
8691
8692 /*!
8693     \since 4.8
8694
8695     Returns the local 8-bit representation of the string as a
8696     QByteArray. The returned byte array is undefined if the string
8697     contains characters not supported by the local 8-bit encoding.
8698
8699     QTextCodec::codecForLocale() is used to perform the conversion from
8700     Unicode. If the locale encoding could not be determined, this function
8701     does the same as toLatin1().
8702
8703     If this string contains any characters that cannot be encoded in the
8704     locale, the returned byte array is undefined. Those characters may be
8705     suppressed or replaced by another.
8706
8707     \sa toAscii(), toLatin1(), toUtf8(), QTextCodec
8708 */
8709 QByteArray QStringRef::toLocal8Bit() const
8710 {
8711 #ifndef QT_NO_TEXTCODEC
8712     if (QTextCodec::codecForLocale())
8713         return QTextCodec::codecForLocale()->fromUnicode(unicode(), length());
8714 #endif // QT_NO_TEXTCODEC
8715     return toLatin1();
8716 }
8717
8718 /*!
8719     \since 4.8
8720
8721     Returns a UTF-8 representation of the string as a QByteArray.
8722
8723     UTF-8 is a Unicode codec and can represent all characters in a Unicode
8724     string like QString.
8725
8726     However, in the Unicode range, there are certain codepoints that are not
8727     considered characters. The Unicode standard reserves the last two
8728     codepoints in each Unicode Plane (U+FFFE, U+FFFF, U+1FFFE, U+1FFFF,
8729     U+2FFFE, etc.), as well as 16 codepoints in the range U+FDD0..U+FDDF,
8730     inclusive, as non-characters. If any of those appear in the string, they
8731     may be discarded and will not appear in the UTF-8 representation, or they
8732     may be replaced by one or more replacement characters.
8733
8734     \sa toAscii(), toLatin1(), toLocal8Bit(), QTextCodec
8735 */
8736 QByteArray QStringRef::toUtf8() const
8737 {
8738     if (isNull())
8739         return QByteArray();
8740
8741     return QUtf8::convertFromUnicode(constData(), length(), 0);
8742 }
8743
8744 /*!
8745     \since 4.8
8746
8747     Returns a UCS-4/UTF-32 representation of the string as a QVector<uint>.
8748
8749     UCS-4 is a Unicode codec and is lossless. All characters from this string
8750     can be encoded in UCS-4.
8751
8752     \sa toAscii(), toLatin1(), toLocal8Bit(), QTextCodec
8753 */
8754 QVector<uint> QStringRef::toUcs4() const
8755 {
8756     QVector<uint> v(length());
8757     uint *a = v.data();
8758     int len = QString::toUcs4_helper(reinterpret_cast<const ushort *>(unicode()), length(), a);
8759     v.resize(len);
8760     return v;
8761 }
8762
8763
8764 /*!
8765     \obsolete
8766     \fn QString Qt::escape(const QString &plain)
8767
8768     \sa QString::toHtmlEscaped()
8769 */
8770
8771 /*!
8772     Converts the plain text string \a plain to a HTML string with
8773     HTML metacharacters \c{<}, \c{>}, \c{&}, and \c{"} replaced by HTML
8774     entities.
8775
8776     Example:
8777
8778     \snippet doc/src/snippets/code/src_corelib_tools_qstring.cpp 7
8779 */
8780 QString QString::toHtmlEscaped() const
8781 {
8782     QString rich;
8783     const int len = length();
8784     rich.reserve(int(len * 1.1));
8785     for (int i = 0; i < len; ++i) {
8786         if (at(i) == QLatin1Char('<'))
8787             rich += QLatin1String("&lt;");
8788         else if (at(i) == QLatin1Char('>'))
8789             rich += QLatin1String("&gt;");
8790         else if (at(i) == QLatin1Char('&'))
8791             rich += QLatin1String("&amp;");
8792         else if (at(i) == QLatin1Char('"'))
8793             rich += QLatin1String("&quot;");
8794         else
8795             rich += at(i);
8796     }
8797     rich.squeeze();
8798     return rich;
8799 }
8800
8801 /*!
8802   \macro QStringLiteral(str)
8803   \relates QString
8804
8805   The macro generates the data for a QString out of \a str at compile time if the compiler supports it.
8806   Creating a QString from it is free in this case, and the generated string data is stored in
8807   the read-only segment of the compiled object file.
8808
8809   For compilers not supporting the creation of compile time strings, QStringLiteral will fall back to
8810   QLatin1String.
8811
8812   The result of the QStringLiteral expression can be cast into a QString.
8813
8814   If you have code looking like:
8815   \code
8816   if (node.hasAttribute("http-contents-length")) //...
8817   \endcode
8818   One temporary QString will be created to be passed as the hasAttribute function parameter.
8819   This can be quite expensive, as it involves a memory allocation and the copy and the conversion
8820   of the data into QString's internal encoding.
8821
8822   This can be avoided by doing
8823   \code
8824   if (node.hasAttribute(QStringLiteral("http-contents-length"))) //...
8825   \endcode
8826   Then the QString's internal data will be generated at compile time and no conversion or allocation
8827   will occur at runtime
8828
8829   Using QStringLiteral instead of a double quoted ascii literal can significantly speed up creation
8830   of QString's from data known at compile time.
8831
8832   If the compiler is C++11 enabled the string \a str can actually contain unicode data.
8833
8834   \note There are still a few cases in which QLatin1String is more efficient than QStringLiteral:
8835   If it is passed to a function that has an overload that takes the QLatin1String directly, without
8836   conversion to QString. For instance, this is the case of QString::operator==
8837   \code
8838   if (attribute.name() == QLatin1String("http-contents-length")) //...
8839   \endcode
8840 */
8841
8842 QT_END_NAMESPACE