Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qstring.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 The Qt Company Ltd.
2// Copyright (C) 2022 Intel Corporation.
3// Copyright (C) 2019 Mail.ru Group.
4// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
5// Qt-Security score:critical reason:data-parser
6
7#include "qstringlist.h"
8#if QT_CONFIG(regularexpression)
9#include "qregularexpression.h"
10#endif
12#include <private/qstringconverter_p.h>
13#include <private/qtools_p.h>
15#include "private/qsimd_p.h"
16#include <qnumeric.h>
17#include <qdatastream.h>
18#include <qlist.h>
19#include "qlocale.h"
20#include "qlocale_p.h"
21#include "qspan.h"
22#include "qstringbuilder.h"
23#include "qstringmatcher.h"
25#include "qdebug.h"
26#include "qendian.h"
27#include "qcollator.h"
28#include "qttypetraits.h"
29
30#ifdef Q_OS_DARWIN
31#include <private/qcore_mac_p.h>
32#endif
33
34#include <private/qfunctions_p.h>
35
36#include <limits.h>
37#include <string.h>
38#include <stdlib.h>
39#include <stdio.h>
40#include <stdarg.h>
41#include <wchar.h>
42
43#include "qchar.cpp"
48#include <QtCore/private/qnumeric_p.h>
49
50#include <algorithm>
51#include <functional>
52
53#ifdef Q_OS_WIN
54# include <qt_windows.h>
55# if !defined(QT_BOOTSTRAPPED) && (defined(QT_NO_CAST_FROM_ASCII) || defined(QT_NO_CAST_TO_ASCII))
56// MSVC requires this, but let's apply it to MinGW compilers too, just in case
57# error "This file cannot be compiled with QT_NO_CAST_{TO,FROM}_ASCII, "
58 "otherwise some QString functions will not get exported."
59# endif
60#endif
61
62#ifdef truncate
63# undef truncate
64#endif
65
66#define REHASH(a)
67 if (sl_minus_1 < sizeof(sl_minus_1) * CHAR_BIT)
68 hashHaystack -= decltype(hashHaystack)(a) << sl_minus_1;
69 hashHaystack <<= 1
70
72
73using namespace Qt::StringLiterals;
74using namespace QtMiscUtils;
75
76const char16_t QString::_empty = 0;
77
78// in qstringmatcher.cpp
79qsizetype qFindStringBoyerMoore(QStringView haystack, qsizetype from, QStringView needle, Qt::CaseSensitivity cs);
80
81namespace {
82enum StringComparisonMode {
83 CompareStringsForEquality,
84 CompareStringsForOrdering
85};
86
87template <typename Pointer>
88char32_t foldCaseHelper(Pointer ch, Pointer start) = delete;
89
90template <>
91char32_t foldCaseHelper<const QChar*>(const QChar* ch, const QChar* start)
92{
93 return foldCase(reinterpret_cast<const char16_t*>(ch),
94 reinterpret_cast<const char16_t*>(start));
95}
96
97template <>
98char32_t foldCaseHelper<const char*>(const char* ch, const char*)
99{
100 return foldCase(char16_t(uchar(*ch)));
101}
102
103template <typename T>
104char16_t valueTypeToUtf16(T t) = delete;
105
106template <>
107char16_t valueTypeToUtf16<QChar>(QChar t)
108{
109 return t.unicode();
110}
111
112template <>
113char16_t valueTypeToUtf16<char>(char t)
114{
115 return char16_t{uchar(t)};
116}
117
118template <typename T>
119static inline bool foldAndCompare(const T a, const T b)
120{
121 return foldCase(a) == b;
122}
123
124/*!
125 \internal
126
127 Returns the index position of the first occurrence of the
128 character \a ch in the string given by \a str and \a len,
129 searching forward from index
130 position \a from. Returns -1 if \a ch could not be found.
131*/
132template <typename Haystack>
133static inline qsizetype qLastIndexOf(Haystack haystack, QChar needle,
134 qsizetype from, Qt::CaseSensitivity cs) noexcept
135{
136 if (haystack.size() == 0)
137 return -1;
138 if (from < 0)
139 from += haystack.size();
140 else if (std::size_t(from) > std::size_t(haystack.size()))
141 from = haystack.size() - 1;
142 if (from >= 0) {
143 char16_t c = needle.unicode();
144 const auto b = haystack.data();
145 auto n = b + from;
146 if (cs == Qt::CaseSensitive) {
147 for (; n >= b; --n)
148 if (valueTypeToUtf16(*n) == c)
149 return n - b;
150 } else {
151 c = foldCase(c);
152 for (; n >= b; --n)
153 if (foldCase(valueTypeToUtf16(*n)) == c)
154 return n - b;
155 }
156 }
157 return -1;
158}
159template <> qsizetype
160qLastIndexOf(QString, QChar, qsizetype, Qt::CaseSensitivity) noexcept = delete; // unwanted, would detach
161
162template<typename Haystack, typename Needle>
163static qsizetype qLastIndexOf(Haystack haystack0, qsizetype from,
164 Needle needle0, Qt::CaseSensitivity cs) noexcept
165{
166 const qsizetype sl = needle0.size();
167 if (sl == 1)
168 return qLastIndexOf(haystack0, needle0.front(), from, cs);
169
170 const qsizetype l = haystack0.size();
171 if (from < 0)
172 from += l;
173 if (from == l && sl == 0)
174 return from;
175 const qsizetype delta = l - sl;
176 if (std::size_t(from) > std::size_t(l) || delta < 0)
177 return -1;
178 if (from > delta)
179 from = delta;
180
181 auto sv = [sl](const typename Haystack::value_type *v) { return Haystack(v, sl); };
182
183 auto haystack = haystack0.data();
184 const auto needle = needle0.data();
185 const auto *end = haystack;
186 haystack += from;
187 const qregisteruint sl_minus_1 = sl ? sl - 1 : 0;
188 const auto *n = needle + sl_minus_1;
189 const auto *h = haystack + sl_minus_1;
190 qregisteruint hashNeedle = 0, hashHaystack = 0;
191
192 if (cs == Qt::CaseSensitive) {
193 for (qsizetype idx = 0; idx < sl; ++idx) {
194 hashNeedle = (hashNeedle << 1) + valueTypeToUtf16(*(n - idx));
195 hashHaystack = (hashHaystack << 1) + valueTypeToUtf16(*(h - idx));
196 }
197 hashHaystack -= valueTypeToUtf16(*haystack);
198
199 while (haystack >= end) {
200 hashHaystack += valueTypeToUtf16(*haystack);
201 if (hashHaystack == hashNeedle
202 && QtPrivate::compareStrings(needle0, sv(haystack), Qt::CaseSensitive) == 0)
203 return haystack - end;
204 --haystack;
205 REHASH(valueTypeToUtf16(haystack[sl]));
206 }
207 } else {
208 for (qsizetype idx = 0; idx < sl; ++idx) {
209 hashNeedle = (hashNeedle << 1) + foldCaseHelper(n - idx, needle);
210 hashHaystack = (hashHaystack << 1) + foldCaseHelper(h - idx, end);
211 }
212 hashHaystack -= foldCaseHelper(haystack, end);
213
214 while (haystack >= end) {
215 hashHaystack += foldCaseHelper(haystack, end);
216 if (hashHaystack == hashNeedle
217 && QtPrivate::compareStrings(sv(haystack), needle0, Qt::CaseInsensitive) == 0)
218 return haystack - end;
219 --haystack;
220 REHASH(foldCaseHelper(haystack + sl, end));
221 }
222 }
223 return -1;
224}
225
226template <typename Haystack, typename Needle>
227bool qt_starts_with_impl(Haystack haystack, Needle needle, Qt::CaseSensitivity cs) noexcept
228{
229 if (haystack.isNull())
230 return needle.isNull();
231 const auto haystackLen = haystack.size();
232 const auto needleLen = needle.size();
233 if (haystackLen == 0)
234 return needleLen == 0;
235 if (needleLen > haystackLen)
236 return false;
237
238 return QtPrivate::compareStrings(haystack.first(needleLen), needle, cs) == 0;
239}
240
241template <typename Haystack, typename Needle>
242bool qt_ends_with_impl(Haystack haystack, Needle needle, Qt::CaseSensitivity cs) noexcept
243{
244 if (haystack.isNull())
245 return needle.isNull();
246 const auto haystackLen = haystack.size();
247 const auto needleLen = needle.size();
248 if (haystackLen == 0)
249 return needleLen == 0;
250 if (haystackLen < needleLen)
251 return false;
252
253 return QtPrivate::compareStrings(haystack.last(needleLen), needle, cs) == 0;
254}
255
256template <typename T>
257static void append_helper(QString &self, T view)
258{
259 const auto strData = view.data();
260 const qsizetype strSize = view.size();
261 auto &d = self.data_ptr();
262 if (strData && strSize > 0) {
263 // the number of UTF-8 code units is always at a minimum equal to the number
264 // of equivalent UTF-16 code units
265 d.detachAndGrow(QArrayData::GrowsAtEnd, strSize, nullptr, nullptr);
266 Q_CHECK_PTR(d.data());
267 Q_ASSERT(strSize <= d.freeSpaceAtEnd());
268
269 auto dst = std::next(d.data(), d.size);
270 if constexpr (std::is_same_v<T, QUtf8StringView>) {
271 dst = QUtf8::convertToUnicode(dst, view);
272 } else if constexpr (std::is_same_v<T, QLatin1StringView>) {
273 QLatin1::convertToUnicode(dst, view);
274 dst += strSize;
275 } else {
276 static_assert(QtPrivate::type_dependent_false<T>(),
277 "Can only operate on UTF-8 and Latin-1");
278 }
279 self.resize(std::distance(d.begin(), dst));
280 } else if (d.isNull() && !view.isNull()) { // special case
281 self = QLatin1StringView("");
282 }
283}
284
285template <uint MaxCount> struct UnrollTailLoop
286{
287 template <typename RetType, typename Functor1, typename Functor2, typename Number>
288 static inline RetType exec(Number count, RetType returnIfExited, Functor1 loopCheck, Functor2 returnIfFailed, Number i = 0)
289 {
290 /* equivalent to:
291 * while (count--) {
292 * if (loopCheck(i))
293 * return returnIfFailed(i);
294 * }
295 * return returnIfExited;
296 */
297
298 if (!count)
299 return returnIfExited;
300
301 bool check = loopCheck(i);
302 if (check)
303 return returnIfFailed(i);
304
305 return UnrollTailLoop<MaxCount - 1>::exec(count - 1, returnIfExited, loopCheck, returnIfFailed, i + 1);
306 }
307
308 template <typename Functor, typename Number>
309 static inline void exec(Number count, Functor code)
310 {
311 /* equivalent to:
312 * for (Number i = 0; i < count; ++i)
313 * code(i);
314 */
315 exec(count, 0, [=](Number i) -> bool { code(i); return false; }, [](Number) { return 0; });
316 }
317};
318template <> template <typename RetType, typename Functor1, typename Functor2, typename Number>
319inline RetType UnrollTailLoop<0>::exec(Number, RetType returnIfExited, Functor1, Functor2, Number)
320{
321 return returnIfExited;
322}
323} // unnamed namespace
324
325/*
326 * Note on the use of SIMD in qstring.cpp:
327 *
328 * Several operations with strings are improved with the use of SIMD code,
329 * since they are repetitive. For MIPS, we have hand-written assembly code
330 * outside of qstring.cpp targeting MIPS DSP and MIPS DSPr2. For ARM and for
331 * x86, we can only use intrinsics and therefore everything is contained in
332 * qstring.cpp. We need to use intrinsics only for those platforms due to the
333 * different compilers and toolchains used, which have different syntax for
334 * assembly sources.
335 *
336 * ** SSE notes: **
337 *
338 * Whenever multiple alternatives are equivalent or near so, we prefer the one
339 * using instructions from SSE2, since SSE2 is guaranteed to be enabled for all
340 * 64-bit builds and we enable it for 32-bit builds by default. Use of higher
341 * SSE versions should be done when there is a clear performance benefit and
342 * requires fallback code to SSE2, if it exists.
343 *
344 * Performance measurement in the past shows that most strings are short in
345 * size and, therefore, do not benefit from alignment prologues. That is,
346 * trying to find a 16-byte-aligned boundary to operate on is often more
347 * expensive than executing the unaligned operation directly. In addition, note
348 * that the QString private data is designed so that the data is stored on
349 * 16-byte boundaries if the system malloc() returns 16-byte aligned pointers
350 * on its own (64-bit glibc on Linux does; 32-bit glibc on Linux returns them
351 * 50% of the time), so skipping the alignment prologue is actually optimizing
352 * for the common case.
353 */
354
355#if defined(__mips_dsp)
356// From qstring_mips_dsp_asm.S
357extern "C" void qt_fromlatin1_mips_asm_unroll4 (char16_t*, const char*, uint);
358extern "C" void qt_fromlatin1_mips_asm_unroll8 (char16_t*, const char*, uint);
359extern "C" void qt_toLatin1_mips_dsp_asm(uchar *dst, const char16_t *src, int length);
360#endif
361
362#if defined(__SSE2__) && defined(Q_CC_GNU)
363// We may overrun the buffer, but that's a false positive:
364// this won't crash nor produce incorrect results
365# define ATTRIBUTE_NO_SANITIZE __attribute__((__no_sanitize_address__, __no_sanitize_thread__))
366#else
367# define ATTRIBUTE_NO_SANITIZE
368#endif
369
370#ifdef __SSE2__
371static constexpr bool UseSse4_1 = bool(qCompilerCpuFeatures & CpuFeatureSSE4_1);
372static constexpr bool UseAvx2 = UseSse4_1 &&
373 (qCompilerCpuFeatures & CpuFeatureArchHaswell) == CpuFeatureArchHaswell;
374
375[[maybe_unused]]
376Q_ALWAYS_INLINE static __m128i mm_load8_zero_extend(const void *ptr)
377{
378 const __m128i *dataptr = static_cast<const __m128i *>(ptr);
379 if constexpr (UseSse4_1) {
380 // use a MOVQ followed by PMOVZXBW
381 // if AVX2 is present, these should combine into a single VPMOVZXBW instruction
382 __m128i data = _mm_loadl_epi64(dataptr);
383 return _mm_cvtepu8_epi16(data);
384 }
385
386 // use MOVQ followed by PUNPCKLBW
387 __m128i data = _mm_loadl_epi64(dataptr);
388 return _mm_unpacklo_epi8(data, _mm_setzero_si128());
389}
390
391[[maybe_unused]] ATTRIBUTE_NO_SANITIZE
392static qsizetype qustrlen_sse2(const char16_t *str) noexcept
393{
394 // find the 16-byte alignment immediately prior or equal to str
395 quintptr misalignment = quintptr(str) & 0xf;
396 Q_ASSERT((misalignment & 1) == 0);
397 const char16_t *ptr = str - (misalignment / 2);
398
399 // load 16 bytes and see if we have a null
400 // (aligned loads can never segfault)
401 const __m128i zeroes = _mm_setzero_si128();
402 __m128i data = _mm_load_si128(reinterpret_cast<const __m128i *>(ptr));
403 __m128i comparison = _mm_cmpeq_epi16(data, zeroes);
404 uint mask = _mm_movemask_epi8(comparison);
405
406 // ignore the result prior to the beginning of str
407 mask >>= misalignment;
408
409 // Have we found something in the first block? Need to handle it now
410 // because of the left shift above.
411 if (mask)
412 return qCountTrailingZeroBits(mask) / sizeof(char16_t);
413
414 constexpr qsizetype Step = sizeof(__m128i) / sizeof(char16_t);
415 qsizetype size = Step - misalignment / sizeof(char16_t);
416
417 size -= Step;
418 do {
419 size += Step;
420 data = _mm_load_si128(reinterpret_cast<const __m128i *>(str + size));
421
422 comparison = _mm_cmpeq_epi16(data, zeroes);
423 mask = _mm_movemask_epi8(comparison);
424 } while (mask == 0);
425
426 // found a null
427 return size + qCountTrailingZeroBits(mask) / sizeof(char16_t);
428}
429
430// Scans from \a ptr to \a end until \a maskval is non-zero. Returns true if
431// the no non-zero was found. Returns false and updates \a ptr to point to the
432// first 16-bit word that has any bit set (note: if the input is 8-bit, \a ptr
433// may be updated to one byte short).
434static bool simdTestMask(const char *&ptr, const char *end, quint32 maskval)
435{
436 auto updatePtr = [&](uint result) {
437 // found a character matching the mask
438 uint idx = qCountTrailingZeroBits(~result);
439 ptr += idx;
440 return false;
441 };
442
443 if constexpr (UseSse4_1) {
444# ifndef Q_OS_QNX // compiler fails in the code below
445 __m128i mask;
446 auto updatePtrSimd = [&](__m128i data) -> bool {
447 __m128i masked = _mm_and_si128(mask, data);
448 __m128i comparison = _mm_cmpeq_epi16(masked, _mm_setzero_si128());
449 uint result = _mm_movemask_epi8(comparison);
450 return updatePtr(result);
451 };
452
453 if constexpr (UseAvx2) {
454 // AVX2 implementation: test 32 bytes at a time
455 const __m256i mask256 = _mm256_broadcastd_epi32(_mm_cvtsi32_si128(maskval));
456 while (ptr + 32 <= end) {
457 __m256i data = _mm256_loadu_si256(reinterpret_cast<const __m256i *>(ptr));
458 if (!_mm256_testz_si256(mask256, data)) {
459 // found a character matching the mask
460 __m256i masked256 = _mm256_and_si256(mask256, data);
461 __m256i comparison256 = _mm256_cmpeq_epi16(masked256, _mm256_setzero_si256());
462 return updatePtr(_mm256_movemask_epi8(comparison256));
463 }
464 ptr += 32;
465 }
466
467 mask = _mm256_castsi256_si128(mask256);
468 } else {
469 // SSE 4.1 implementation: test 32 bytes at a time (two 16-byte
470 // comparisons, unrolled)
471 mask = _mm_set1_epi32(maskval);
472 while (ptr + 32 <= end) {
473 __m128i data1 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(ptr));
474 __m128i data2 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(ptr + 16));
475 if (!_mm_testz_si128(mask, data1))
476 return updatePtrSimd(data1);
477
478 ptr += 16;
479 if (!_mm_testz_si128(mask, data2))
480 return updatePtrSimd(data2);
481 ptr += 16;
482 }
483 }
484
485 // AVX2 and SSE4.1: final 16-byte comparison
486 if (ptr + 16 <= end) {
487 __m128i data1 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(ptr));
488 if (!_mm_testz_si128(mask, data1))
489 return updatePtrSimd(data1);
490 ptr += 16;
491 }
492
493 // and final 8-byte comparison
494 if (ptr + 8 <= end) {
495 __m128i data1 = _mm_loadl_epi64(reinterpret_cast<const __m128i *>(ptr));
496 if (!_mm_testz_si128(mask, data1))
497 return updatePtrSimd(data1);
498 ptr += 8;
499 }
500
501 return true;
502# endif // QNX
503 }
504
505 // SSE2 implementation: test 16 bytes at a time.
506 const __m128i mask = _mm_set1_epi32(maskval);
507 while (ptr + 16 <= end) {
508 __m128i data = _mm_loadu_si128(reinterpret_cast<const __m128i *>(ptr));
509 __m128i masked = _mm_and_si128(mask, data);
510 __m128i comparison = _mm_cmpeq_epi16(masked, _mm_setzero_si128());
511 quint16 result = _mm_movemask_epi8(comparison);
512 if (result != 0xffff)
513 return updatePtr(result);
514 ptr += 16;
515 }
516
517 // and one 8-byte comparison
518 if (ptr + 8 <= end) {
519 __m128i data = _mm_loadl_epi64(reinterpret_cast<const __m128i *>(ptr));
520 __m128i masked = _mm_and_si128(mask, data);
521 __m128i comparison = _mm_cmpeq_epi16(masked, _mm_setzero_si128());
522 quint8 result = _mm_movemask_epi8(comparison);
523 if (result != 0xff)
524 return updatePtr(result);
525 ptr += 8;
526 }
527
528 return true;
529}
530
531template <StringComparisonMode Mode, typename Char> [[maybe_unused]]
532static int ucstrncmp_sse2(const char16_t *a, const Char *b, size_t l)
533{
534 static_assert(std::is_unsigned_v<Char>);
535
536 // Using the PMOVMSKB instruction, we get two bits for each UTF-16 character
537 // we compare. This lambda helps extract the code unit.
538 static const auto codeUnitAt = [](const auto *n, qptrdiff idx) -> int {
539 constexpr int Stride = 2;
540 // this is the same as:
541 // return n[idx / Stride];
542 // but using pointer arithmetic to avoid the compiler dividing by two
543 // and multiplying by two in the case of char16_t (we know idx is even,
544 // but the compiler does not). This is not UB.
545
546 auto ptr = reinterpret_cast<const uchar *>(n);
547 ptr += idx / (Stride / sizeof(*n));
548 return *reinterpret_cast<decltype(n)>(ptr);
549 };
550 auto difference = [a, b](uint mask, qptrdiff offset) {
551 if (Mode == CompareStringsForEquality)
552 return 1;
553 uint idx = qCountTrailingZeroBits(mask);
554 return codeUnitAt(a + offset, idx) - codeUnitAt(b + offset, idx);
555 };
556
557 static const auto load8Chars = [](const auto *ptr) {
558 if (sizeof(*ptr) == 2)
559 return _mm_loadu_si128(reinterpret_cast<const __m128i *>(ptr));
560 __m128i chunk = _mm_loadl_epi64(reinterpret_cast<const __m128i *>(ptr));
561 return _mm_unpacklo_epi8(chunk, _mm_setzero_si128());
562 };
563 static const auto load4Chars = [](const auto *ptr) {
564 if (sizeof(*ptr) == 2)
565 return _mm_loadl_epi64(reinterpret_cast<const __m128i *>(ptr));
566 __m128i chunk = _mm_cvtsi32_si128(qFromUnaligned<quint32>(ptr));
567 return _mm_unpacklo_epi8(chunk, _mm_setzero_si128());
568 };
569
570 // we're going to read a[0..15] and b[0..15] (32 bytes)
571 auto processChunk16Chars = [a, b](qptrdiff offset) -> uint {
572 if constexpr (UseAvx2) {
573 __m256i a_data = _mm256_loadu_si256(reinterpret_cast<const __m256i *>(a + offset));
574 __m256i b_data;
575 if (sizeof(Char) == 1) {
576 // expand to UTF-16 via zero-extension
577 __m128i chunk = _mm_loadu_si128(reinterpret_cast<const __m128i *>(b + offset));
578 b_data = _mm256_cvtepu8_epi16(chunk);
579 } else {
580 b_data = _mm256_loadu_si256(reinterpret_cast<const __m256i *>(b + offset));
581 }
582 __m256i result = _mm256_cmpeq_epi16(a_data, b_data);
583 return _mm256_movemask_epi8(result);
584 }
585
586 __m128i a_data1 = load8Chars(a + offset);
587 __m128i a_data2 = load8Chars(a + offset + 8);
588 __m128i b_data1, b_data2;
589 if (sizeof(Char) == 1) {
590 // expand to UTF-16 via unpacking
591 __m128i b_data = _mm_loadu_si128(reinterpret_cast<const __m128i *>(b + offset));
592 b_data1 = _mm_unpacklo_epi8(b_data, _mm_setzero_si128());
593 b_data2 = _mm_unpackhi_epi8(b_data, _mm_setzero_si128());
594 } else {
595 b_data1 = load8Chars(b + offset);
596 b_data2 = load8Chars(b + offset + 8);
597 }
598 __m128i result1 = _mm_cmpeq_epi16(a_data1, b_data1);
599 __m128i result2 = _mm_cmpeq_epi16(a_data2, b_data2);
600 return _mm_movemask_epi8(result1) | _mm_movemask_epi8(result2) << 16;
601 };
602
603 if (l >= sizeof(__m256i) / sizeof(char16_t)) {
604 qptrdiff offset = 0;
605 for ( ; l >= offset + sizeof(__m256i) / sizeof(char16_t); offset += sizeof(__m256i) / sizeof(char16_t)) {
606 uint mask = ~processChunk16Chars(offset);
607 if (mask)
608 return difference(mask, offset);
609 }
610
611 // maybe overlap the last 32 bytes
612 if (size_t(offset) < l) {
613 offset = l - sizeof(__m256i) / sizeof(char16_t);
614 uint mask = ~processChunk16Chars(offset);
615 return mask ? difference(mask, offset) : 0;
616 }
617 } else if (l >= 4) {
618 __m128i a_data1, b_data1;
619 __m128i a_data2, b_data2;
620 int width;
621 if (l >= 8) {
622 width = 8;
623 a_data1 = load8Chars(a);
624 b_data1 = load8Chars(b);
625 a_data2 = load8Chars(a + l - width);
626 b_data2 = load8Chars(b + l - width);
627 } else {
628 // we're going to read a[0..3] and b[0..3] (8 bytes)
629 width = 4;
630 a_data1 = load4Chars(a);
631 b_data1 = load4Chars(b);
632 a_data2 = load4Chars(a + l - width);
633 b_data2 = load4Chars(b + l - width);
634 }
635
636 __m128i result = _mm_cmpeq_epi16(a_data1, b_data1);
637 ushort mask = ~_mm_movemask_epi8(result);
638 if (mask)
639 return difference(mask, 0);
640
641 result = _mm_cmpeq_epi16(a_data2, b_data2);
642 mask = ~_mm_movemask_epi8(result);
643 if (mask)
644 return difference(mask, l - width);
645 } else {
646 // reset l
647 l &= 3;
648
649 const auto lambda = [=](size_t i) -> int {
650 return a[i] - b[i];
651 };
652 return UnrollTailLoop<3>::exec(l, 0, lambda, lambda);
653 }
654 return 0;
655}
656#endif
657
658Q_NEVER_INLINE
659qsizetype QtPrivate::qustrlen(const char16_t *str) noexcept
660{
661#if defined(__SSE2__) && !(defined(__SANITIZE_ADDRESS__) || __has_feature(address_sanitizer)) && !(defined(__SANITIZE_THREAD__) || __has_feature(thread_sanitizer))
662 return qustrlen_sse2(str);
663#endif
664
665 if (sizeof(wchar_t) == sizeof(char16_t))
666 return wcslen(reinterpret_cast<const wchar_t *>(str));
667
668 qsizetype result = 0;
669 while (*str++)
670 ++result;
671 return result;
672}
673
674qsizetype QtPrivate::qustrnlen(const char16_t *str, qsizetype maxlen) noexcept
675{
676 return qustrchr({ str, maxlen }, u'\0') - str;
677}
678
679/*!
680 * \internal
681 *
682 * Searches for character \a c in the string \a str and returns a pointer to
683 * it. Unlike strchr() and wcschr() (but like glibc's strchrnul()), if the
684 * character is not found, this function returns a pointer to the end of the
685 * string -- that is, \c{str.end()}.
686 */
688const char16_t *QtPrivate::qustrchr(QStringView str, char16_t c) noexcept
689{
690 const char16_t *n = str.utf16();
691 const char16_t *e = n + str.size();
692
693#ifdef __SSE2__
694 bool loops = true;
695 // Using the PMOVMSKB instruction, we get two bits for each character
696 // we compare.
697 __m128i mch;
698 if constexpr (UseAvx2) {
699 // we're going to read n[0..15] (32 bytes)
700 __m256i mch256 = _mm256_set1_epi32(c | (c << 16));
701 for (const char16_t *next = n + 16; next <= e; n = next, next += 16) {
702 __m256i data = _mm256_loadu_si256(reinterpret_cast<const __m256i *>(n));
703 __m256i result = _mm256_cmpeq_epi16(data, mch256);
704 uint mask = uint(_mm256_movemask_epi8(result));
705 if (mask) {
706 uint idx = qCountTrailingZeroBits(mask);
707 return n + idx / 2;
708 }
709 }
710 loops = false;
711 mch = _mm256_castsi256_si128(mch256);
712 } else {
713 mch = _mm_set1_epi32(c | (c << 16));
714 }
715
716 auto hasMatch = [mch, &n](__m128i data, ushort validityMask) {
717 __m128i result = _mm_cmpeq_epi16(data, mch);
718 uint mask = uint(_mm_movemask_epi8(result));
719 if ((mask & validityMask) == 0)
720 return false;
721 uint idx = qCountTrailingZeroBits(mask);
722 n += idx / 2;
723 return true;
724 };
725
726 // we're going to read n[0..7] (16 bytes)
727 for (const char16_t *next = n + 8; next <= e; n = next, next += 8) {
728 __m128i data = _mm_loadu_si128(reinterpret_cast<const __m128i *>(n));
729 if (hasMatch(data, 0xffff))
730 return n;
731
732 if (!loops) {
733 n += 8;
734 break;
735 }
736 }
737
738# if !defined(__OPTIMIZE_SIZE__)
739 // we're going to read n[0..3] (8 bytes)
740 if (e - n > 3) {
741 __m128i data = _mm_loadl_epi64(reinterpret_cast<const __m128i *>(n));
742 if (hasMatch(data, 0xff))
743 return n;
744
745 n += 4;
746 }
747
748 return UnrollTailLoop<3>::exec(e - n, e,
749 [=](qsizetype i) { return n[i] == c; },
750 [=](qsizetype i) { return n + i; });
751# endif
752#elif defined(__ARM_NEON__)
753 const uint16x8_t vmask = qvsetq_n_u16(1, 1 << 1, 1 << 2, 1 << 3, 1 << 4, 1 << 5, 1 << 6, 1 << 7);
754 const uint16x8_t ch_vec = vdupq_n_u16(c);
755 for (const char16_t *next = n + 8; next <= e; n = next, next += 8) {
756 uint16x8_t data = vld1q_u16(reinterpret_cast<const uint16_t *>(n));
757 uint mask = vaddvq_u16(vandq_u16(vceqq_u16(data, ch_vec), vmask));
758 if (ushort(mask)) {
759 // found a match
760 return n + qCountTrailingZeroBits(mask);
761 }
762 }
763#endif // aarch64
764
765 return std::find(n, e, c);
766}
767
768/*!
769 * \internal
770 *
771 * Searches case-insensitively for character \a c in the string \a str and
772 * returns a pointer to it. Iif the character is not found, this function
773 * returns a pointer to the end of the string -- that is, \c{str.end()}.
774 */
776const char16_t *QtPrivate::qustrcasechr(QStringView str, char16_t c) noexcept
777{
778 const QChar *n = str.begin();
779 const QChar *e = str.end();
780 c = foldCase(c);
781 auto it = std::find_if(n, e, [c](auto ch) { return foldAndCompare(ch, QChar(c)); });
782 return reinterpret_cast<const char16_t *>(it);
783}
784
785// Note: ptr on output may be off by one and point to a preceding US-ASCII
786// character. Usually harmless.
787bool qt_is_ascii(const char *&ptr, const char *end) noexcept
788{
789#if defined(__SSE2__)
790 // Testing for the high bit can be done efficiently with just PMOVMSKB
791 bool loops = true;
792 if constexpr (UseAvx2) {
793 while (ptr + 32 <= end) {
794 __m256i data = _mm256_loadu_si256(reinterpret_cast<const __m256i *>(ptr));
795 quint32 mask = _mm256_movemask_epi8(data);
796 if (mask) {
797 uint idx = qCountTrailingZeroBits(mask);
798 ptr += idx;
799 return false;
800 }
801 ptr += 32;
802 }
803 loops = false;
804 }
805
806 while (ptr + 16 <= end) {
807 __m128i data = _mm_loadu_si128(reinterpret_cast<const __m128i *>(ptr));
808 quint32 mask = _mm_movemask_epi8(data);
809 if (mask) {
810 uint idx = qCountTrailingZeroBits(mask);
811 ptr += idx;
812 return false;
813 }
814 ptr += 16;
815
816 if (!loops)
817 break;
818 }
819 if (ptr + 8 <= end) {
820 __m128i data = _mm_loadl_epi64(reinterpret_cast<const __m128i *>(ptr));
821 quint8 mask = _mm_movemask_epi8(data);
822 if (mask) {
823 uint idx = qCountTrailingZeroBits(mask);
824 ptr += idx;
825 return false;
826 }
827 ptr += 8;
828 }
829#endif
830
831 while (ptr + 4 <= end) {
832 quint32 data = qFromUnaligned<quint32>(ptr);
833 if (data &= 0x80808080U) {
834 uint idx = QSysInfo::ByteOrder == QSysInfo::BigEndian
835 ? qCountLeadingZeroBits(data)
836 : qCountTrailingZeroBits(data);
837 ptr += idx / 8;
838 return false;
839 }
840 ptr += 4;
841 }
842
843 while (ptr != end) {
844 if (quint8(*ptr) & 0x80)
845 return false;
846 ++ptr;
847 }
848 return true;
849}
850
851bool QtPrivate::isAscii(QLatin1StringView s) noexcept
852{
853 const char *ptr = s.begin();
854 const char *end = s.end();
855
856 return qt_is_ascii(ptr, end);
857}
858
859static bool isAscii_helper(const char16_t *&ptr, const char16_t *end)
860{
861#ifdef __SSE2__
862 const char *ptr8 = reinterpret_cast<const char *>(ptr);
863 const char *end8 = reinterpret_cast<const char *>(end);
864 bool ok = simdTestMask(ptr8, end8, 0xff80ff80);
865 ptr = reinterpret_cast<const char16_t *>(ptr8);
866 if (!ok)
867 return false;
868#endif
869
870 while (ptr != end) {
871 if (*ptr & 0xff80)
872 return false;
873 ++ptr;
874 }
875 return true;
876}
877
878bool QtPrivate::isAscii(QStringView s) noexcept
879{
880 const char16_t *ptr = s.utf16();
881 const char16_t *end = ptr + s.size();
882
883 return isAscii_helper(ptr, end);
884}
885
886bool QtPrivate::isLatin1(QStringView s) noexcept
887{
888 const char16_t *ptr = s.utf16();
889 const char16_t *end = ptr + s.size();
890
891#ifdef __SSE2__
892 const char *ptr8 = reinterpret_cast<const char *>(ptr);
893 const char *end8 = reinterpret_cast<const char *>(end);
894 if (!simdTestMask(ptr8, end8, 0xff00ff00))
895 return false;
896 ptr = reinterpret_cast<const char16_t *>(ptr8);
897#endif
898
899 while (ptr != end) {
900 if (*ptr++ > 0xff)
901 return false;
902 }
903 return true;
904}
905
906bool QtPrivate::isValidUtf16(QStringView s) noexcept
907{
908 constexpr char32_t InvalidCodePoint = UINT_MAX;
909
910 QStringIterator i(s);
911 while (i.hasNext()) {
912 const char32_t c = i.next(InvalidCodePoint);
913 if (c == InvalidCodePoint)
914 return false;
915 }
916
917 return true;
918}
919
920// conversion between Latin 1 and UTF-16
921Q_CORE_EXPORT void qt_from_latin1(char16_t *dst, const char *str, size_t size) noexcept
922{
923 /* SIMD:
924 * Unpacking with SSE has been shown to improve performance on recent CPUs
925 * The same method gives no improvement with NEON. On Aarch64, clang will do the vectorization
926 * itself in exactly the same way as one would do it with intrinsics.
927 */
928#if defined(__SSE2__)
929 // we're going to read str[offset..offset+15] (16 bytes)
930 const __m128i nullMask = _mm_setzero_si128();
931 auto processOneChunk = [=](qptrdiff offset) {
932 const __m128i chunk = _mm_loadu_si128((const __m128i*)(str + offset)); // load
933 if constexpr (UseAvx2) {
934 // zero extend to an YMM register
935 const __m256i extended = _mm256_cvtepu8_epi16(chunk);
936
937 // store
938 _mm256_storeu_si256((__m256i*)(dst + offset), extended);
939 } else {
940 // unpack the first 8 bytes, padding with zeros
941 const __m128i firstHalf = _mm_unpacklo_epi8(chunk, nullMask);
942 _mm_storeu_si128((__m128i*)(dst + offset), firstHalf); // store
943
944 // unpack the last 8 bytes, padding with zeros
945 const __m128i secondHalf = _mm_unpackhi_epi8 (chunk, nullMask);
946 _mm_storeu_si128((__m128i*)(dst + offset + 8), secondHalf); // store
947 }
948 };
949
950 const char *e = str + size;
951 if (size >= sizeof(__m128i)) {
952 qptrdiff offset = 0;
953 for ( ; str + offset + sizeof(__m128i) <= e; offset += sizeof(__m128i))
954 processOneChunk(offset);
955 if (str + offset < e)
956 processOneChunk(size - sizeof(__m128i));
957 return;
958 }
959
960# if !defined(__OPTIMIZE_SIZE__)
961 if (size >= 4) {
962 // two overlapped loads & stores, of either 64-bit or of 32-bit
963 if (size >= 8) {
964 const __m128i unpacked1 = mm_load8_zero_extend(str);
965 const __m128i unpacked2 = mm_load8_zero_extend(str + size - 8);
966 _mm_storeu_si128(reinterpret_cast<__m128i *>(dst), unpacked1);
967 _mm_storeu_si128(reinterpret_cast<__m128i *>(dst + size - 8), unpacked2);
968 } else {
969 const __m128i chunk1 = _mm_cvtsi32_si128(qFromUnaligned<quint32>(str));
970 const __m128i chunk2 = _mm_cvtsi32_si128(qFromUnaligned<quint32>(str + size - 4));
971 const __m128i unpacked1 = _mm_unpacklo_epi8(chunk1, nullMask);
972 const __m128i unpacked2 = _mm_unpacklo_epi8(chunk2, nullMask);
973 _mm_storel_epi64(reinterpret_cast<__m128i *>(dst), unpacked1);
974 _mm_storel_epi64(reinterpret_cast<__m128i *>(dst + size - 4), unpacked2);
975 }
976 return;
977 } else {
978 size = size % 4;
979 return UnrollTailLoop<3>::exec(qsizetype(size), [=](qsizetype i) { dst[i] = uchar(str[i]); });
980 }
981# endif
982#endif
983#if defined(__mips_dsp)
984 static_assert(sizeof(qsizetype) == sizeof(int),
985 "oops, the assembler implementation needs to be called in a loop");
986 if (size > 20)
987 qt_fromlatin1_mips_asm_unroll8(dst, str, size);
988 else
989 qt_fromlatin1_mips_asm_unroll4(dst, str, size);
990#else
991 while (size--)
992 *dst++ = (uchar)*str++;
993#endif
994}
995
996static QVarLengthArray<char16_t> qt_from_latin1_to_qvla(QLatin1StringView str)
997{
998 const qsizetype len = str.size();
999 QVarLengthArray<char16_t> arr(len);
1000 qt_from_latin1(arr.data(), str.data(), len);
1001 return arr;
1002}
1003
1004template <bool Checked>
1005static void qt_to_latin1_internal(uchar *dst, const char16_t *src, qsizetype length)
1006{
1007#if defined(__SSE2__)
1008 auto questionMark256 = []() {
1009 if constexpr (UseAvx2)
1010 return _mm256_broadcastw_epi16(_mm_cvtsi32_si128('?'));
1011 else
1012 return 0;
1013 }();
1014 auto outOfRange256 = []() {
1015 if constexpr (UseAvx2)
1016 return _mm256_broadcastw_epi16(_mm_cvtsi32_si128(0x100));
1017 else
1018 return 0;
1019 }();
1020 __m128i questionMark, outOfRange;
1021 if constexpr (UseAvx2) {
1022 questionMark = _mm256_castsi256_si128(questionMark256);
1023 outOfRange = _mm256_castsi256_si128(outOfRange256);
1024 } else {
1025 questionMark = _mm_set1_epi16('?');
1026 outOfRange = _mm_set1_epi16(0x100);
1027 }
1028
1029 auto mergeQuestionMarks = [=](__m128i chunk) {
1030 if (!Checked)
1031 return chunk;
1032
1033 // SSE has no compare instruction for unsigned comparison.
1034 if constexpr (UseSse4_1) {
1035 // We use an unsigned uc = qMin(uc, 0x100) and then compare for equality.
1036 chunk = _mm_min_epu16(chunk, outOfRange);
1037 const __m128i offLimitMask = _mm_cmpeq_epi16(chunk, outOfRange);
1038 chunk = _mm_blendv_epi8(chunk, questionMark, offLimitMask);
1039 return chunk;
1040 }
1041 // The variables must be shiffted + 0x8000 to be compared
1042 const __m128i signedBitOffset = _mm_set1_epi16(short(0x8000));
1043 const __m128i thresholdMask = _mm_set1_epi16(short(0xff + 0x8000));
1044
1045 const __m128i signedChunk = _mm_add_epi16(chunk, signedBitOffset);
1046 const __m128i offLimitMask = _mm_cmpgt_epi16(signedChunk, thresholdMask);
1047
1048 // offLimitQuestionMark contains '?' for each 16 bits that was off-limit
1049 // the 16 bits that were correct contains zeros
1050 const __m128i offLimitQuestionMark = _mm_and_si128(offLimitMask, questionMark);
1051
1052 // correctBytes contains the bytes that were in limit
1053 // the 16 bits that were off limits contains zeros
1054 const __m128i correctBytes = _mm_andnot_si128(offLimitMask, chunk);
1055
1056 // merge offLimitQuestionMark and correctBytes to have the result
1057 chunk = _mm_or_si128(correctBytes, offLimitQuestionMark);
1058
1059 Q_UNUSED(outOfRange);
1060 return chunk;
1061 };
1062
1063 // we're going to read to src[offset..offset+15] (16 bytes)
1064 auto loadChunkAt = [=](qptrdiff offset) {
1065 __m128i chunk1, chunk2;
1066 if constexpr (UseAvx2) {
1067 __m256i chunk = _mm256_loadu_si256(reinterpret_cast<const __m256i *>(src + offset));
1068 if (Checked) {
1069 // See mergeQuestionMarks lambda above for details
1070 chunk = _mm256_min_epu16(chunk, outOfRange256);
1071 const __m256i offLimitMask = _mm256_cmpeq_epi16(chunk, outOfRange256);
1072 chunk = _mm256_blendv_epi8(chunk, questionMark256, offLimitMask);
1073 }
1074
1075 chunk2 = _mm256_extracti128_si256(chunk, 1);
1076 chunk1 = _mm256_castsi256_si128(chunk);
1077 } else {
1078 chunk1 = _mm_loadu_si128((const __m128i*)(src + offset)); // load
1079 chunk1 = mergeQuestionMarks(chunk1);
1080
1081 chunk2 = _mm_loadu_si128((const __m128i*)(src + offset + 8)); // load
1082 chunk2 = mergeQuestionMarks(chunk2);
1083 }
1084
1085 // pack the two vector to 16 x 8bits elements
1086 return _mm_packus_epi16(chunk1, chunk2);
1087 };
1088
1089 if (size_t(length) >= sizeof(__m128i)) {
1090 // because of possible overlapping, we won't process the last chunk in the loop
1091 qptrdiff offset = 0;
1092 for ( ; offset + 2 * sizeof(__m128i) < size_t(length); offset += sizeof(__m128i))
1093 _mm_storeu_si128(reinterpret_cast<__m128i *>(dst + offset), loadChunkAt(offset));
1094
1095 // overlapped conversion of the last full chunk and the tail
1096 __m128i last1 = loadChunkAt(offset);
1097 __m128i last2 = loadChunkAt(length - sizeof(__m128i));
1098 _mm_storeu_si128(reinterpret_cast<__m128i *>(dst + offset), last1);
1099 _mm_storeu_si128(reinterpret_cast<__m128i *>(dst + length - sizeof(__m128i)), last2);
1100 return;
1101 }
1102
1103# if !defined(__OPTIMIZE_SIZE__)
1104 if (length >= 4) {
1105 // this code is fine even for in-place conversion because we load both
1106 // before any store
1107 if (length >= 8) {
1108 __m128i chunk1 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(src));
1109 __m128i chunk2 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(src + length - 8));
1110 chunk1 = mergeQuestionMarks(chunk1);
1111 chunk2 = mergeQuestionMarks(chunk2);
1112
1113 // pack, where the upper half is ignored
1114 const __m128i result1 = _mm_packus_epi16(chunk1, chunk1);
1115 const __m128i result2 = _mm_packus_epi16(chunk2, chunk2);
1116 _mm_storel_epi64(reinterpret_cast<__m128i *>(dst), result1);
1117 _mm_storel_epi64(reinterpret_cast<__m128i *>(dst + length - 8), result2);
1118 } else {
1119 __m128i chunk1 = _mm_loadl_epi64(reinterpret_cast<const __m128i *>(src));
1120 __m128i chunk2 = _mm_loadl_epi64(reinterpret_cast<const __m128i *>(src + length - 4));
1121 chunk1 = mergeQuestionMarks(chunk1);
1122 chunk2 = mergeQuestionMarks(chunk2);
1123
1124 // pack, we'll zero the upper three quarters
1125 const __m128i result1 = _mm_packus_epi16(chunk1, chunk1);
1126 const __m128i result2 = _mm_packus_epi16(chunk2, chunk2);
1127 qToUnaligned(_mm_cvtsi128_si32(result1), dst);
1128 qToUnaligned(_mm_cvtsi128_si32(result2), dst + length - 4);
1129 }
1130 return;
1131 }
1132
1133 length = length % 4;
1134 return UnrollTailLoop<3>::exec(length, [=](qsizetype i) {
1135 if (Checked)
1136 dst[i] = (src[i]>0xff) ? '?' : (uchar) src[i];
1137 else
1138 dst[i] = src[i];
1139 });
1140# else
1141 length = length % 16;
1142# endif // optimize size
1143#elif defined(__ARM_NEON__)
1144 // Refer to the documentation of the SSE2 implementation.
1145 // This uses exactly the same method as for SSE except:
1146 // 1) neon has unsigned comparison
1147 // 2) packing is done to 64 bits (8 x 8bits component).
1148 if (length >= 16) {
1149 const qsizetype chunkCount = length >> 3; // divided by 8
1150 const uint16x8_t questionMark = vdupq_n_u16('?'); // set
1151 const uint16x8_t thresholdMask = vdupq_n_u16(0xff); // set
1152 for (qsizetype i = 0; i < chunkCount; ++i) {
1153 uint16x8_t chunk = vld1q_u16((uint16_t *)src); // load
1154 src += 8;
1155
1156 if (Checked) {
1157 const uint16x8_t offLimitMask = vcgtq_u16(chunk, thresholdMask); // chunk > thresholdMask
1158 const uint16x8_t offLimitQuestionMark = vandq_u16(offLimitMask, questionMark); // offLimitMask & questionMark
1159 const uint16x8_t correctBytes = vbicq_u16(chunk, offLimitMask); // !offLimitMask & chunk
1160 chunk = vorrq_u16(correctBytes, offLimitQuestionMark); // correctBytes | offLimitQuestionMark
1161 }
1162 const uint8x8_t result = vmovn_u16(chunk); // narrowing move->packing
1163 vst1_u8(dst, result); // store
1164 dst += 8;
1165 }
1166 length = length % 8;
1167 }
1168#endif
1169#if defined(__mips_dsp)
1170 static_assert(sizeof(qsizetype) == sizeof(int),
1171 "oops, the assembler implementation needs to be called in a loop");
1172 qt_toLatin1_mips_dsp_asm(dst, src, length);
1173#else
1174 while (length--) {
1175 if (Checked)
1176 *dst++ = (*src>0xff) ? '?' : (uchar) *src;
1177 else
1178 *dst++ = *src;
1179 ++src;
1180 }
1181#endif
1182}
1183
1184void qt_to_latin1(uchar *dst, const char16_t *src, qsizetype length)
1185{
1186 qt_to_latin1_internal<true>(dst, src, length);
1187}
1188
1189void qt_to_latin1_unchecked(uchar *dst, const char16_t *src, qsizetype length)
1190{
1191 qt_to_latin1_internal<false>(dst, src, length);
1192}
1193
1194// Unicode case-insensitive comparison (argument order matches QStringView)
1195Q_NEVER_INLINE static int ucstricmp(qsizetype alen, const char16_t *a, qsizetype blen, const char16_t *b)
1196{
1197 if (a == b)
1198 return qt_lencmp(alen, blen);
1199
1200 qsizetype l = qMin(alen, blen);
1201 qsizetype i;
1202 for (i = 0; i < l; ++i) {
1203// qDebug() << Qt::hex << alast << blast;
1204// qDebug() << Qt::hex << "*a=" << *a << "alast=" << alast << "folded=" << foldCase (*a, alast);
1205// qDebug() << Qt::hex << "*b=" << *b << "blast=" << blast << "folded=" << foldCase (*b, blast);
1206 int diff = foldCase(a + i, a) - foldCase(b + i, b);
1207 if ((diff))
1208 return diff;
1209 }
1210 if (i == alen) {
1211 if (i == blen)
1212 return 0;
1213 return -1;
1214 }
1215 return 1;
1216}
1217
1218// Case-insensitive comparison between a QStringView and a QLatin1StringView
1219// (argument order matches those types)
1220Q_NEVER_INLINE static int ucstricmp(qsizetype alen, const char16_t *a, qsizetype blen, const char *b)
1221{
1222 qsizetype l = qMin(alen, blen);
1223 qsizetype i;
1224 for (i = 0; i < l; ++i) {
1225 int diff = foldCase(a[i]) - foldCase(char16_t{uchar(b[i])});
1226 if ((diff))
1227 return diff;
1228 }
1229 if (i == alen) {
1230 if (i == blen)
1231 return 0;
1232 return -1;
1233 }
1234 return 1;
1235}
1236
1237// Case-insensitive comparison between a Unicode string and a UTF-8 string
1238Q_NEVER_INLINE static int ucstricmp8(const char *utf8, const char *utf8end, const QChar *utf16, const QChar *utf16end)
1239{
1240 auto src1 = reinterpret_cast<const qchar8_t *>(utf8);
1241 auto end1 = reinterpret_cast<const qchar8_t *>(utf8end);
1242 QStringIterator src2(utf16, utf16end);
1243
1244 while (src1 < end1 && src2.hasNext()) {
1245 char32_t uc1 = QChar::toCaseFolded(QUtf8Functions::nextUcs4FromUtf8(src1, end1));
1246 char32_t uc2 = QChar::toCaseFolded(src2.next());
1247 int diff = uc1 - uc2; // can't underflow
1248 if (diff)
1249 return diff;
1250 }
1251
1252 // the shorter string sorts first
1253 return (end1 > src1) - int(src2.hasNext());
1254}
1255
1256#if defined(__mips_dsp)
1257// From qstring_mips_dsp_asm.S
1258extern "C" int qt_ucstrncmp_mips_dsp_asm(const char16_t *a,
1259 const char16_t *b,
1260 unsigned len);
1261#endif
1262
1263// Unicode case-sensitive compare two same-sized strings
1264template <StringComparisonMode Mode>
1265static int ucstrncmp(const char16_t *a, const char16_t *b, size_t l)
1266{
1267 // This function isn't memcmp() because that can return the wrong sorting
1268 // result in little-endian architectures: 0x00ff must sort before 0x0100,
1269 // but the bytes in memory are FF 00 and 00 01.
1270
1271#ifndef __OPTIMIZE_SIZE__
1272# if defined(__mips_dsp)
1273 static_assert(sizeof(uint) == sizeof(size_t));
1274 if (l >= 8) {
1275 return qt_ucstrncmp_mips_dsp_asm(a, b, l);
1276 }
1277# elif defined(__SSE2__)
1278 return ucstrncmp_sse2<Mode>(a, b, l);
1279# elif defined(__ARM_NEON__)
1280 if (l >= 8) {
1281 const char16_t *end = a + l;
1282 const uint16x8_t mask = qvsetq_n_u16( 1, 1 << 1, 1 << 2, 1 << 3, 1 << 4, 1 << 5, 1 << 6, 1 << 7 );
1283 while (end - a > 7) {
1284 uint16x8_t da = vld1q_u16(reinterpret_cast<const uint16_t *>(a));
1285 uint16x8_t db = vld1q_u16(reinterpret_cast<const uint16_t *>(b));
1286
1287 uint8_t r = ~(uint8_t)vaddvq_u16(vandq_u16(vceqq_u16(da, db), mask));
1288 if (r) {
1289 // found a different QChar
1290 if (Mode == CompareStringsForEquality)
1291 return 1;
1292 uint idx = qCountTrailingZeroBits(r);
1293 return a[idx] - b[idx];
1294 }
1295 a += 8;
1296 b += 8;
1297 }
1298 l &= 7;
1299 }
1300 const auto lambda = [=](size_t i) -> int {
1301 return a[i] - b[i];
1302 };
1303 return UnrollTailLoop<7>::exec(l, 0, lambda, lambda);
1304# endif // MIPS DSP or __SSE2__ or __ARM_NEON__
1305#endif // __OPTIMIZE_SIZE__
1306
1307 if (Mode == CompareStringsForEquality || QSysInfo::ByteOrder == QSysInfo::BigEndian)
1308 return memcmp(a, b, l * sizeof(char16_t));
1309
1310 for (size_t i = 0; i < l; ++i) {
1311 if (int diff = a[i] - b[i])
1312 return diff;
1313 }
1314 return 0;
1315}
1316
1317template <StringComparisonMode Mode>
1318static int ucstrncmp(const char16_t *a, const char *b, size_t l)
1319{
1320 const uchar *c = reinterpret_cast<const uchar *>(b);
1321 const char16_t *uc = a;
1322 const char16_t *e = uc + l;
1323
1324#if defined(__SSE2__) && !defined(__OPTIMIZE_SIZE__)
1325 return ucstrncmp_sse2<Mode>(uc, c, l);
1326#endif
1327
1328 while (uc < e) {
1329 int diff = *uc - *c;
1330 if (diff)
1331 return diff;
1332 uc++, c++;
1333 }
1334
1335 return 0;
1336}
1337
1338// Unicode case-sensitive equality
1339template <typename Char2>
1340static bool ucstreq(const char16_t *a, size_t alen, const Char2 *b)
1341{
1342 return ucstrncmp<CompareStringsForEquality>(a, b, alen) == 0;
1343}
1344
1345// Unicode case-sensitive comparison
1346template <typename Char2>
1347static int ucstrcmp(const char16_t *a, size_t alen, const Char2 *b, size_t blen)
1348{
1349 const size_t l = qMin(alen, blen);
1350 int cmp = ucstrncmp<CompareStringsForOrdering>(a, b, l);
1351 return cmp ? cmp : qt_lencmp(alen, blen);
1352}
1353
1355
1356static int latin1nicmp(const char *lhsChar, qsizetype lSize, const char *rhsChar, qsizetype rSize)
1357{
1358 // We're called with QLatin1StringView's .data() and .size():
1359 Q_ASSERT(lSize >= 0 && rSize >= 0);
1360 if (!lSize)
1361 return rSize ? -1 : 0;
1362 if (!rSize)
1363 return 1;
1364 const qsizetype size = std::min(lSize, rSize);
1365
1366 Q_ASSERT(lhsChar && rhsChar); // since both lSize and rSize are positive
1367 for (qsizetype i = 0; i < size; i++) {
1368 if (int res = CaseInsensitiveL1::difference(lhsChar[i], rhsChar[i]))
1369 return res;
1370 }
1371 return qt_lencmp(lSize, rSize);
1372}
1373
1374bool QtPrivate::equalStrings(QStringView lhs, QStringView rhs) noexcept
1375{
1376 Q_ASSERT(lhs.size() == rhs.size());
1377 return ucstreq(lhs.utf16(), lhs.size(), rhs.utf16());
1378}
1379
1380bool QtPrivate::equalStrings(QStringView lhs, QLatin1StringView rhs) noexcept
1381{
1382 Q_ASSERT(lhs.size() == rhs.size());
1383 return ucstreq(lhs.utf16(), lhs.size(), rhs.latin1());
1384}
1385
1386bool QtPrivate::equalStrings(QLatin1StringView lhs, QStringView rhs) noexcept
1387{
1388 return QtPrivate::equalStrings(rhs, lhs);
1389}
1390
1391bool QtPrivate::equalStrings(QLatin1StringView lhs, QLatin1StringView rhs) noexcept
1392{
1393 Q_ASSERT(lhs.size() == rhs.size());
1394 return (!lhs.size() || memcmp(lhs.data(), rhs.data(), lhs.size()) == 0);
1395}
1396
1397bool QtPrivate::equalStrings(QBasicUtf8StringView<false> lhs, QStringView rhs) noexcept
1398{
1399 return QUtf8::compareUtf8(lhs, rhs) == 0;
1400}
1401
1402bool QtPrivate::equalStrings(QStringView lhs, QBasicUtf8StringView<false> rhs) noexcept
1403{
1404 return QtPrivate::equalStrings(rhs, lhs);
1405}
1406
1407bool QtPrivate::equalStrings(QLatin1StringView lhs, QBasicUtf8StringView<false> rhs) noexcept
1408{
1409 return QUtf8::compareUtf8(QByteArrayView(rhs), lhs) == 0;
1410}
1411
1412bool QtPrivate::equalStrings(QBasicUtf8StringView<false> lhs, QLatin1StringView rhs) noexcept
1413{
1414 return QtPrivate::equalStrings(rhs, lhs);
1415}
1416
1417bool QtPrivate::equalStrings(QBasicUtf8StringView<false> lhs, QBasicUtf8StringView<false> rhs) noexcept
1418{
1419#if QT_VERSION >= QT_VERSION_CHECK(7, 0, 0) || defined(QT_BOOTSTRAPPED) || defined(QT_STATIC)
1420 Q_ASSERT(lhs.size() == rhs.size());
1421#else
1422 // operator== didn't enforce size prior to Qt 6.2
1423 if (lhs.size() != rhs.size())
1424 return false;
1425#endif
1426 return (!lhs.size() || memcmp(lhs.data(), rhs.data(), lhs.size()) == 0);
1427}
1428
1429bool QAnyStringView::equal(QAnyStringView lhs, QAnyStringView rhs) noexcept
1430{
1431 if (lhs.size() != rhs.size() && lhs.isUtf8() == rhs.isUtf8())
1432 return false;
1433 return lhs.visit([rhs](auto lhs) {
1434 return rhs.visit([lhs](auto rhs) {
1435 return QtPrivate::equalStrings(lhs, rhs);
1436 });
1437 });
1438}
1439
1440/*!
1441 \relates QStringView
1442 \internal
1443 \since 5.10
1444
1445 Returns an integer that compares to 0 as \a lhs compares to \a rhs.
1446
1447 \include qstring.qdocinc {search-comparison-case-sensitivity} {comparison}
1448
1449 Case-sensitive comparison is based exclusively on the numeric Unicode values
1450 of the characters and is very fast, but is not what a human would expect.
1451 Consider sorting user-visible strings with QString::localeAwareCompare().
1452
1453 \sa {Comparing Strings}
1454*/
1455int QtPrivate::compareStrings(QStringView lhs, QStringView rhs, Qt::CaseSensitivity cs) noexcept
1456{
1457 if (cs == Qt::CaseSensitive)
1458 return ucstrcmp(lhs.utf16(), lhs.size(), rhs.utf16(), rhs.size());
1459 return ucstricmp(lhs.size(), lhs.utf16(), rhs.size(), rhs.utf16());
1460}
1461
1462/*!
1463 \relates QStringView
1464 \internal
1465 \since 5.10
1466 \overload
1467
1468 Returns an integer that compares to 0 as \a lhs compares to \a rhs.
1469
1470 \include qstring.qdocinc {search-comparison-case-sensitivity} {comparison}
1471
1472 Case-sensitive comparison is based exclusively on the numeric Unicode values
1473 of the characters and is very fast, but is not what a human would expect.
1474 Consider sorting user-visible strings with QString::localeAwareCompare().
1475
1476 \sa {Comparing Strings}
1477*/
1478int QtPrivate::compareStrings(QStringView lhs, QLatin1StringView rhs, Qt::CaseSensitivity cs) noexcept
1479{
1480 if (cs == Qt::CaseSensitive)
1481 return ucstrcmp(lhs.utf16(), lhs.size(), rhs.latin1(), rhs.size());
1482 return ucstricmp(lhs.size(), lhs.utf16(), rhs.size(), rhs.latin1());
1483}
1484
1485/*!
1486 \relates QStringView
1487 \internal
1488 \since 6.0
1489 \overload
1490*/
1491int QtPrivate::compareStrings(QStringView lhs, QBasicUtf8StringView<false> rhs, Qt::CaseSensitivity cs) noexcept
1492{
1493 return -compareStrings(rhs, lhs, cs);
1494}
1495
1496/*!
1497 \relates QStringView
1498 \internal
1499 \since 5.10
1500 \overload
1501*/
1502int QtPrivate::compareStrings(QLatin1StringView lhs, QStringView rhs, Qt::CaseSensitivity cs) noexcept
1503{
1504 return -compareStrings(rhs, lhs, cs);
1505}
1506
1507/*!
1508 \relates QStringView
1509 \internal
1510 \since 5.10
1511 \overload
1512
1513 Returns an integer that compares to 0 as \a lhs compares to \a rhs.
1514
1515 \include qstring.qdocinc {search-comparison-case-sensitivity} {comparison}
1516
1517 Case-sensitive comparison is based exclusively on the numeric Latin-1 values
1518 of the characters and is very fast, but is not what a human would expect.
1519 Consider sorting user-visible strings with QString::localeAwareCompare().
1520
1521 \sa {Comparing Strings}
1522*/
1523int QtPrivate::compareStrings(QLatin1StringView lhs, QLatin1StringView rhs, Qt::CaseSensitivity cs) noexcept
1524{
1525 if (lhs.isEmpty())
1526 return qt_lencmp(qsizetype(0), rhs.size());
1527 if (rhs.isEmpty())
1528 return qt_lencmp(lhs.size(), qsizetype(0));
1529 if (cs == Qt::CaseInsensitive)
1530 return latin1nicmp(lhs.data(), lhs.size(), rhs.data(), rhs.size());
1531 const auto l = std::min(lhs.size(), rhs.size());
1532 int r = memcmp(lhs.data(), rhs.data(), l);
1533 return r ? r : qt_lencmp(lhs.size(), rhs.size());
1534}
1535
1536/*!
1537 \relates QStringView
1538 \internal
1539 \since 6.0
1540 \overload
1541*/
1542int QtPrivate::compareStrings(QLatin1StringView lhs, QBasicUtf8StringView<false> rhs, Qt::CaseSensitivity cs) noexcept
1543{
1544 return -QUtf8::compareUtf8(QByteArrayView(rhs), lhs, cs);
1545}
1546
1547/*!
1548 \relates QStringView
1549 \internal
1550 \since 6.0
1551 \overload
1552*/
1553int QtPrivate::compareStrings(QBasicUtf8StringView<false> lhs, QStringView rhs, Qt::CaseSensitivity cs) noexcept
1554{
1555 if (cs == Qt::CaseSensitive)
1556 return QUtf8::compareUtf8(lhs, rhs);
1557 return ucstricmp8(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());
1558}
1559
1560/*!
1561 \relates QStringView
1562 \internal
1563 \since 6.0
1564 \overload
1565*/
1566int QtPrivate::compareStrings(QBasicUtf8StringView<false> lhs, QLatin1StringView rhs, Qt::CaseSensitivity cs) noexcept
1567{
1568 return -compareStrings(rhs, lhs, cs);
1569}
1570
1571/*!
1572 \relates QStringView
1573 \internal
1574 \since 6.0
1575 \overload
1576*/
1577int QtPrivate::compareStrings(QBasicUtf8StringView<false> lhs, QBasicUtf8StringView<false> rhs, Qt::CaseSensitivity cs) noexcept
1578{
1579 return QUtf8::compareUtf8(QByteArrayView(lhs), QByteArrayView(rhs), cs);
1580}
1581
1582int QAnyStringView::compare(QAnyStringView lhs, QAnyStringView rhs, Qt::CaseSensitivity cs) noexcept
1583{
1584 return lhs.visit([rhs, cs](auto lhs) {
1585 return rhs.visit([lhs, cs](auto rhs) {
1586 return QtPrivate::compareStrings(lhs, rhs, cs);
1587 });
1588 });
1589}
1590
1591// ### Qt 7: do not allow anything but ASCII digits
1592// in arg()'s replacements.
1593#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0) && !defined(QT_BOOTSTRAPPED)
1594static bool supportUnicodeDigitValuesInArg()
1595{
1596 static const bool result = []() {
1597 static const char supportUnicodeDigitValuesEnvVar[]
1598 = "QT_USE_UNICODE_DIGIT_VALUES_IN_STRING_ARG";
1599
1600 if (qEnvironmentVariableIsSet(supportUnicodeDigitValuesEnvVar))
1601 return qEnvironmentVariableIntValue(supportUnicodeDigitValuesEnvVar) != 0;
1602
1603#if QT_VERSION < QT_VERSION_CHECK(6, 6, 0) // keep it in sync with the test
1604 return true;
1605#else
1606 return false;
1607#endif
1608 }();
1609
1610 return result;
1611}
1612#endif
1613
1614static int qArgDigitValue(QChar ch) noexcept
1615{
1616#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0) && !defined(QT_BOOTSTRAPPED)
1617 if (supportUnicodeDigitValuesInArg())
1618 return ch.digitValue();
1619#endif
1620 if (ch >= u'0' && ch <= u'9')
1621 return int(ch.unicode() - u'0');
1622 return -1;
1623}
1624
1625#if QT_CONFIG(regularexpression)
1626Q_DECL_COLD_FUNCTION
1627static void qtWarnAboutInvalidRegularExpression(const QRegularExpression &re, const char *cls, const char *method)
1628{
1629 extern void qtWarnAboutInvalidRegularExpression(const QString &pattern, const char *cls, const char *method);
1630 qtWarnAboutInvalidRegularExpression(re.pattern(), cls, method);
1631}
1632#endif
1633
1634/*!
1635 \macro QT_RESTRICTED_CAST_FROM_ASCII
1636 \relates QString
1637
1638 Disables most automatic conversions from source literals and 8-bit data
1639 to unicode QStrings, but allows the use of
1640 the \c{QChar(char)} and \c{QString(const char (&ch)[N]} constructors,
1641 and the \c{QString::operator=(const char (&ch)[N])} assignment operator.
1642 This gives most of the type-safety benefits of \l QT_NO_CAST_FROM_ASCII
1643 but does not require user code to wrap character and string literals
1644 with QLatin1Char, QLatin1StringView or similar.
1645
1646 Using this macro together with source strings outside the 7-bit range,
1647 non-literals, or literals with embedded NUL characters is undefined.
1648
1649 \sa QT_NO_CAST_FROM_ASCII, QT_NO_CAST_TO_ASCII
1650*/
1651
1652/*!
1653 \macro QT_NO_CAST_FROM_ASCII
1654 \relates QString
1655 \relates QChar
1656
1657 Disables automatic conversions from 8-bit strings (\c{char *}) to Unicode
1658 QStrings, as well as from 8-bit \c{char} types (\c{char} and
1659 \c{unsigned char}) to QChar.
1660
1661 \sa QT_NO_CAST_TO_ASCII, QT_RESTRICTED_CAST_FROM_ASCII,
1662 QT_NO_CAST_FROM_BYTEARRAY
1663*/
1664
1665/*!
1666 \macro QT_NO_CAST_TO_ASCII
1667 \relates QString
1668
1669 Disables automatic conversion from QString to 8-bit strings (\c{char *}).
1670
1671 \sa QT_NO_CAST_FROM_ASCII, QT_RESTRICTED_CAST_FROM_ASCII,
1672 QT_NO_CAST_FROM_BYTEARRAY
1673*/
1674
1675/*!
1676 \macro QT_ASCII_CAST_WARNINGS
1677 \internal
1678 \relates QString
1679
1680 This macro can be defined to force a warning whenever a function is
1681 called that automatically converts between unicode and 8-bit encodings.
1682
1683 Note: This only works for compilers that support warnings for
1684 deprecated API.
1685
1686 \sa QT_NO_CAST_TO_ASCII, QT_NO_CAST_FROM_ASCII, QT_RESTRICTED_CAST_FROM_ASCII
1687*/
1688
1689/*!
1690 \class QString
1691 \inmodule QtCore
1692 \reentrant
1693
1694 \brief The QString class provides a Unicode character string.
1695
1696 \ingroup tools
1697 \ingroup shared
1698 \ingroup string-processing
1699
1700 \compares strong
1701 \compareswith strong QChar QLatin1StringView {const char16_t *} \
1702 QStringView QUtf8StringView
1703 \endcompareswith
1704 \compareswith strong QByteArray QByteArrayView {const char *}
1705 When comparing with byte arrays, their content is interpreted as UTF-8.
1706 \endcompareswith
1707
1708 QString stores a string of 16-bit \l{QChar}s, where each QChar
1709 corresponds to one UTF-16 code unit. (Unicode characters
1710 with code values above 65535 are stored using surrogate pairs,
1711 that is, two consecutive \l{QChar}s.)
1712
1713 \l{Unicode} is an international standard that supports most of the
1714 writing systems in use today. It is a superset of US-ASCII (ANSI
1715 X3.4-1986) and Latin-1 (ISO 8859-1), and all the US-ASCII/Latin-1
1716 characters are available at the same code positions.
1717
1718 Behind the scenes, QString uses \l{implicit sharing}
1719 (copy-on-write) to reduce memory usage and to avoid the needless
1720 copying of data. This also helps reduce the inherent overhead of
1721 storing 16-bit characters instead of 8-bit characters.
1722
1723 In addition to QString, Qt also provides the QByteArray class to
1724 store raw bytes and traditional 8-bit '\\0'-terminated strings.
1725 For most purposes, QString is the class you want to use. It is
1726 used throughout the Qt API, and the Unicode support ensures that
1727 your applications are easy to translate if you want to expand
1728 your application's market at some point. Two prominent cases
1729 where QByteArray is appropriate are when you need to store raw
1730 binary data, and when memory conservation is critical (like in
1731 embedded systems).
1732
1733 \section1 Initializing a string
1734
1735 One way to initialize a QString is to pass a \c{const char
1736 *} to its constructor. For example, the following code creates a
1737 QString of size 5 containing the data "Hello":
1738
1739 \snippet qstring/main.cpp 0
1740
1741 QString converts the \c{const char *} data into Unicode using the
1742 fromUtf8() function.
1743
1744 In all of the QString functions that take \c{const char *}
1745 parameters, the \c{const char *} is interpreted as a classic
1746 C-style \c{'\\0'}-terminated string. Except where the function's
1747 name overtly indicates some other encoding, such \c{const char *}
1748 parameters are assumed to be encoded in UTF-8.
1749
1750 Since Qt 6.4, it is also possible to initialize QStrings using
1751 the \l {Qt::Literals::StringLiterals::operator""_s()} and
1752 \l {Qt::Literals::StringLiterals::operator""_L1()} literal
1753 operators. In many cases, using the literals results in
1754 \l{More efficient string construction}{more efficient string construction}.
1755
1756
1757 You can also provide string data as an array of \l{QChar}s:
1758
1759 \snippet qstring/main.cpp 1
1760
1761 QString makes a deep copy of the QChar data, so you can modify it
1762 later without experiencing side effects. You can avoid taking a
1763 deep copy of the character data by using QStringView or
1764 QString::fromRawData() instead.
1765
1766 Another approach is to set the size of the string using resize()
1767 and to initialize the data character per character. QString uses
1768 0-based indexes, just like C++ arrays. To access the character at
1769 a particular index position, you can use \l operator[](). On
1770 non-\c{const} strings, \l operator[]() returns a reference to a
1771 character that can be used on the left side of an assignment. For
1772 example:
1773
1774 \snippet qstring/main.cpp 2
1775
1776 For read-only access, an alternative syntax is to use the at()
1777 function:
1778
1779 \snippet qstring/main.cpp 3
1780
1781 The at() function can be faster than \l operator[]() because it
1782 never causes a \l{deep copy} to occur. Alternatively, use the
1783 first(), last(), or sliced() functions to extract several characters
1784 at a time.
1785
1786 A QString can embed '\\0' characters (QChar::Null). The size()
1787 function always returns the size of the whole string, including
1788 embedded '\\0' characters.
1789
1790 After a call to the resize() function, newly allocated characters
1791 have undefined values. To set all the characters in the string to
1792 a particular value, use the fill() function.
1793
1794 QString provides dozens of overloads designed to simplify string
1795 usage. For example, if you want to compare a QString with a string
1796 literal, you can write code like this and it will work as expected:
1797
1798 \snippet qstring/main.cpp 4
1799
1800 You can also pass string literals to functions that take QStrings
1801 as arguments, invoking the QString(const char *)
1802 constructor. Similarly, you can pass a QString to a function that
1803 takes a \c{const char *} argument using the \l qPrintable() macro,
1804 which returns the given QString as a \c{const char *}. This is
1805 equivalent to calling toLocal8Bit().\l{QByteArray::}{constData()}
1806 on the QString.
1807
1808 \section1 Manipulating string data
1809
1810 QString provides the following basic functions for modifying the
1811 character data: append(), prepend(), insert(), replace(), and
1812 remove(). For example:
1813
1814 \snippet qstring/main.cpp 5
1815
1816 In the above example, the replace() function's first two arguments are the
1817 position from which to start replacing and the number of characters that
1818 should be replaced.
1819
1820 When data-modifying functions increase the size of the string,
1821 QString may reallocate the memory in which it holds its data. When
1822 this happens, QString expands by more than it immediately needs so as
1823 to have space for further expansion without reallocation until the size
1824 of the string has significantly increased.
1825
1826 The insert(), remove(), and, when replacing a sub-string with one of
1827 different size, replace() functions can be slow (\l{linear time}) for
1828 large strings because they require moving many characters in the string
1829 by at least one position in memory.
1830
1831 If you are building a QString gradually and know in advance
1832 approximately how many characters the QString will contain, you
1833 can call reserve(), asking QString to preallocate a certain amount
1834 of memory. You can also call capacity() to find out how much
1835 memory the QString actually has allocated.
1836
1837 QString provides \l{STL-style iterators} (QString::const_iterator and
1838 QString::iterator). In practice, iterators are handy when working with
1839 generic algorithms provided by the C++ standard library.
1840
1841 \note Iterators over a QString, and references to individual characters
1842 within one, cannot be relied on to remain valid when any non-\c{const}
1843 method of the QString is called. Accessing such an iterator or reference
1844 after the call to a non-\c{const} method leads to undefined behavior. When
1845 stability for iterator-like functionality is required, you should use
1846 indexes instead of iterators, as they are not tied to QString's internal
1847 state and thus do not get invalidated.
1848
1849 \note Due to \l{implicit sharing}, the first non-\c{const} operator or
1850 function used on a given QString may cause it to internally perform a deep
1851 copy of its data. This invalidates all iterators over the string and
1852 references to individual characters within it. Do not call non-const
1853 functions while keeping iterators. Accessing an iterator or reference
1854 after it has been invalidated leads to undefined behavior. See the
1855 \l{Implicit sharing iterator problem} section for more information.
1856
1857 A frequent requirement is to remove or simplify the spacing between
1858 visible characters in a string. The characters that make up that spacing
1859 are those for which \l {QChar::}{isSpace()} returns \c true, such as
1860 the simple space \c{' '}, the horizontal tab \c{'\\t'} and the newline \c{'\\n'}.
1861 To obtain a copy of a string leaving out any spacing from its start and end,
1862 use \l trimmed(). To also replace each sequence of spacing characters within
1863 the string with a simple space, \c{' '}, use \l simplified().
1864
1865 If you want to find all occurrences of a particular character or
1866 substring in a QString, use the indexOf() or lastIndexOf()
1867 functions.The former searches forward, the latter searches backward.
1868 Either can be told an index position from which to start their search.
1869 Each returns the index position of the character or substring if they
1870 find it; otherwise, they return -1. For example, here is a typical loop
1871 that finds all occurrences of a particular substring:
1872
1873 \snippet qstring/main.cpp 6
1874
1875 QString provides many functions for converting numbers into
1876 strings and strings into numbers. See the arg() functions, the
1877 setNum() functions, the number() static functions, and the
1878 toInt(), toDouble(), and similar functions.
1879
1880 To get an uppercase or lowercase version of a string, use toUpper() or
1881 toLower().
1882
1883 Lists of strings are handled by the QStringList class. You can
1884 split a string into a list of strings using the split() function,
1885 and join a list of strings into a single string with an optional
1886 separator using QStringList::join(). You can obtain a filtered list
1887 from a string list by selecting the entries in it that contain a
1888 particular substring or match a particular QRegularExpression.
1889 See QStringList::filter() for details.
1890
1891 \section1 Querying string data
1892
1893 To see if a QString starts or ends with a particular substring, use
1894 startsWith() or endsWith(). To check whether a QString contains a
1895 specific character or substring, use the contains() function. To
1896 find out how many times a particular character or substring occurs
1897 in a string, use count().
1898
1899 To obtain a pointer to the actual character data, call data() or
1900 constData(). These functions return a pointer to the beginning of
1901 the QChar data. The pointer is guaranteed to remain valid until a
1902 non-\c{const} function is called on the QString.
1903
1904 \section2 Comparing strings
1905
1906 QStrings can be compared using overloaded operators such as \l
1907 operator<(), \l operator<=(), \l operator==(), \l operator>=(),
1908 and so on. The comparison is based exclusively on the lexicographical
1909 order of the two strings, seen as sequences of UTF-16 code units.
1910 It is very fast but is not what a human would expect; the
1911 QString::localeAwareCompare() function is usually a better choice for
1912 sorting user-interface strings, when such a comparison is available.
1913
1914 When Qt is linked with the ICU library (which it usually is), its
1915 locale-aware sorting is used. Otherwise, platform-specific solutions
1916 are used:
1917 \list
1918 \li On Windows, localeAwareCompare() uses the current user locale,
1919 as set in the \uicontrol{regional} and \uicontrol{language}
1920 options portion of \uicontrol{Control Panel}.
1921 \li On \macos and iOS, \l localeAwareCompare() compares according
1922 to the \uicontrol{Order for sorted lists} setting in the
1923 \uicontrol{International preferences} panel.
1924 \li On other Unix-like systems, the comparison falls back to the
1925 system library's \c strcoll().
1926 \endlist
1927
1928 \section1 Converting between encoded string data and QString
1929
1930 QString provides the following functions that return a
1931 \c{const char *} version of the string as QByteArray: toUtf8(),
1932 toLatin1(), and toLocal8Bit().
1933
1934 \list
1935 \li toLatin1() returns a Latin-1 (ISO 8859-1) encoded 8-bit string.
1936 \li toUtf8() returns a UTF-8 encoded 8-bit string. UTF-8 is a
1937 superset of US-ASCII (ANSI X3.4-1986) that supports the entire
1938 Unicode character set through multibyte sequences.
1939 \li toLocal8Bit() returns an 8-bit string using the system's local
1940 encoding. This is the same as toUtf8() on Unix systems.
1941 \endlist
1942
1943 To convert from one of these encodings, QString provides
1944 fromLatin1(), fromUtf8(), and fromLocal8Bit(). Other
1945 encodings are supported through the QStringEncoder and QStringDecoder
1946 classes.
1947
1948 As mentioned above, QString provides a lot of functions and
1949 operators that make it easy to interoperate with \c{const char *}
1950 strings. But this functionality is a double-edged sword: It makes
1951 QString more convenient to use if all strings are US-ASCII or
1952 Latin-1, but there is always the risk that an implicit conversion
1953 from or to \c{const char *} is done using the wrong 8-bit
1954 encoding. To minimize these risks, you can turn off these implicit
1955 conversions by defining some of the following preprocessor symbols:
1956
1957 \list
1958 \li \l QT_NO_CAST_FROM_ASCII disables automatic conversions from
1959 C string literals and pointers to Unicode.
1960 \li \l QT_RESTRICTED_CAST_FROM_ASCII allows automatic conversions
1961 from C characters and character arrays but disables automatic
1962 conversions from character pointers to Unicode.
1963 \li \l QT_NO_CAST_TO_ASCII disables automatic conversion from QString
1964 to C strings.
1965 \endlist
1966
1967 You then need to explicitly call fromUtf8(), fromLatin1(),
1968 or fromLocal8Bit() to construct a QString from an
1969 8-bit string, or use the lightweight QLatin1StringView class. For
1970 example:
1971
1972 \snippet code/src_corelib_text_qstring.cpp 1
1973
1974 Similarly, you must call toLatin1(), toUtf8(), or
1975 toLocal8Bit() explicitly to convert the QString to an 8-bit
1976 string.
1977
1978 \table 100 %
1979 \header
1980 \li Note for C Programmers
1981
1982 \row
1983 \li
1984 Due to C++'s type system and the fact that QString is
1985 \l{implicitly shared}, QStrings may be treated like \c{int}s or
1986 other basic types. For example:
1987
1988 \snippet qstring/main.cpp 7
1989
1990 The \c result variable is a normal variable allocated on the
1991 stack. When \c return is called, and because we're returning by
1992 value, the copy constructor is called and a copy of the string is
1993 returned. No actual copying takes place thanks to the implicit
1994 sharing.
1995
1996 \endtable
1997
1998 \section1 Distinction between null and empty strings
1999
2000 For historical reasons, QString distinguishes between null
2001 and empty strings. A \e null string is a string that is
2002 initialized using QString's default constructor or by passing
2003 \nullptr to the constructor. An \e empty string is any
2004 string with size 0. A null string is always empty, but an empty
2005 string isn't necessarily null:
2006
2007 \snippet qstring/main.cpp 8
2008
2009 All functions except isNull() treat null strings the same as empty
2010 strings. For example, toUtf8().\l{QByteArray::}{constData()} returns a valid pointer
2011 (not \nullptr) to a '\\0' character for a null string. We
2012 recommend that you always use the isEmpty() function and avoid isNull().
2013
2014 \section1 Number formats
2015
2016 When a QString::arg() \c{'%'} format specifier includes the \c{'L'} locale
2017 qualifier, and the base is ten (its default), the default locale is
2018 used. This can be set using \l{QLocale::setDefault()}. For more refined
2019 control of localized string representations of numbers, see
2020 QLocale::toString(). All other number formatting done by QString follows the
2021 C locale's representation of numbers.
2022
2023 When QString::arg() applies left-padding to numbers, the fill character
2024 \c{'0'} is treated specially. If the number is negative, its minus sign
2025 appears before the zero-padding. If the field is localized, the
2026 locale-appropriate zero character is used in place of \c{'0'}. For
2027 floating-point numbers, this special treatment only applies if the number is
2028 finite.
2029
2030 \section2 Floating-point formats
2031
2032 In member functions (for example, arg() and number()) that format floating-point
2033 numbers (\c float or \c double) as strings, the representation used can be
2034 controlled by a choice of \e format and \e precision, whose meanings are as
2035 for \l {QLocale::toString(double, char, int)}.
2036
2037 If the selected \e format includes an exponent, localized forms follow the
2038 locale's convention on digits in the exponent. For non-localized formatting,
2039 the exponent shows its sign and includes at least two digits, left-padding
2040 with zero if needed.
2041
2042 \section1 More efficient string construction
2043
2044 Many strings are known at compile time. The QString constructor from
2045 C++ string literals will copy the contents of the string,
2046 treating the contents as UTF-8. This requires memory allocation and
2047 re-encoding string data, operations that will happen at runtime.
2048 If the string data is known at compile time, you can use the QStringLiteral
2049 macro or similarly \c{operator""_s} to create QString's payload at compile
2050 time instead.
2051
2052 Using the QString \c{'+'} operator, it is easy to construct a
2053 complex string from multiple substrings. You will often write code
2054 like this:
2055
2056 \snippet qstring/stringbuilder.cpp 0
2057
2058 There is nothing wrong with either of these string constructions,
2059 but there are a few hidden inefficiencies:
2060
2061 First, repeated use of the \c{'+'} operator may lead to
2062 multiple memory allocations. When concatenating \e{n} substrings,
2063 where \e{n > 2}, there can be as many as \e{n - 1} calls to the
2064 memory allocator.
2065
2066 These allocations can be optimized by an internal class
2067 \c{QStringBuilder}. This class is marked
2068 internal and does not appear in the documentation, because you
2069 aren't meant to instantiate it in your code. Its use will be
2070 automatic, as described below.
2071
2072 \c{QStringBuilder} uses expression templates and reimplements the
2073 \c{'%'} operator so that when you use \c{'%'} for string
2074 concatenation instead of \c{'+'}, multiple substring
2075 concatenations will be postponed until the final result is about
2076 to be assigned to a QString. At this point, the amount of memory
2077 required for the final result is known. The memory allocator is
2078 then called \e{once} to get the required space, and the substrings
2079 are copied into it one by one.
2080
2081 Additional efficiency is gained by inlining and reducing reference
2082 counting (the QString created from a \c{QStringBuilder}
2083 has a ref count of 1, whereas QString::append() needs an extra
2084 test).
2085
2086 There are two ways you can access this improved method of string
2087 construction. The straightforward way is to include
2088 \c{QStringBuilder} wherever you want to use it and use the
2089 \c{'%'} operator instead of \c{'+'} when concatenating strings:
2090
2091 \snippet qstring/stringbuilder.cpp 5
2092
2093 A more global approach, which is more convenient but not entirely
2094 source-compatible, is to define \c QT_USE_QSTRINGBUILDER (by adding
2095 it to the compiler flags) at build time. This will make concatenating
2096 strings with \c{'+'} work the same way as \c{QStringBuilder's} \c{'%'}.
2097
2098 \note Using automatic type deduction (for example, by using the \c
2099 auto keyword) with the result of string concatenation when QStringBuilder
2100 is enabled will show that the concatenation is indeed an object of a
2101 QStringBuilder specialization:
2102
2103 \snippet qstring/stringbuilder.cpp 6
2104
2105 This does not cause any harm, as QStringBuilder will implicitly convert to
2106 QString when required. If this is undesirable, then one should specify
2107 the necessary types instead of having the compiler deduce them:
2108
2109 \snippet qstring/stringbuilder.cpp 7
2110
2111 \section1 Maximum size and out-of-memory conditions
2112
2113 The maximum size of QString depends on the architecture. Most 64-bit
2114 systems can allocate more than 2 GB of memory, with a typical limit
2115 of 2^63 bytes. The actual value also depends on the overhead required for
2116 managing the data block. As a result, you can expect a maximum size
2117 of 2 GB minus overhead on 32-bit platforms and 2^63 bytes minus overhead
2118 on 64-bit platforms. The number of elements that can be stored in a
2119 QString is this maximum size divided by the size of QChar.
2120
2121 When memory allocation fails, QString throws a \c std::bad_alloc
2122 exception if the application was compiled with exception support.
2123 Out-of-memory conditions in Qt containers are the only cases where Qt
2124 will throw exceptions. If exceptions are disabled, then running out of
2125 memory is undefined behavior.
2126
2127 \note Target operating systems may impose limits on how much memory an
2128 application can allocate, in total, or on the size of individual allocations.
2129 This may further restrict the size of string a QString can hold.
2130 Mitigating or controlling the behavior these limits cause is beyond the
2131 scope of the Qt API.
2132
2133 \sa {Which string class to use?}, fromRawData(), QChar, QStringView,
2134 QLatin1StringView, QByteArray
2135*/
2136
2137/*! \typedef QString::ConstIterator
2138
2139 Qt-style synonym for QString::const_iterator.
2140*/
2141
2142/*! \typedef QString::Iterator
2143
2144 Qt-style synonym for QString::iterator.
2145*/
2146
2147/*! \typedef QString::const_iterator
2148
2149 \sa QString::iterator
2150*/
2151
2152/*! \typedef QString::iterator
2153
2154 \sa QString::const_iterator
2155*/
2156
2157/*! \typedef QString::const_reverse_iterator
2158 \since 5.6
2159
2160 \sa QString::reverse_iterator, QString::const_iterator
2161*/
2162
2163/*! \typedef QString::reverse_iterator
2164 \since 5.6
2165
2166 \sa QString::const_reverse_iterator, QString::iterator
2167*/
2168
2169/*!
2170 \typedef QString::size_type
2171*/
2172
2173/*!
2174 \typedef QString::difference_type
2175*/
2176
2177/*!
2178 \typedef QString::const_reference
2179*/
2180/*!
2181 \typedef QString::reference
2182*/
2183
2184/*!
2185 \typedef QString::const_pointer
2186
2187 The QString::const_pointer typedef provides an STL-style
2188 const pointer to a QString element (QChar).
2189*/
2190/*!
2191 \typedef QString::pointer
2192
2193 The QString::pointer typedef provides an STL-style
2194 pointer to a QString element (QChar).
2195*/
2196
2197/*!
2198 \typedef QString::value_type
2199*/
2200
2201/*! \fn QString::iterator QString::begin()
2202
2203 Returns an \l{STL-style iterators}{STL-style iterator} pointing to the
2204 first character in the string.
2205
2206//! [iterator-invalidation-func-desc]
2207 \warning The returned iterator is invalidated on detachment or when the
2208 QString is modified.
2209//! [iterator-invalidation-func-desc]
2210
2211 \sa constBegin(), end()
2212*/
2213
2214/*! \fn QString::const_iterator QString::begin() const
2215
2216 \overload begin()
2217*/
2218
2219/*! \fn QString::const_iterator QString::cbegin() const
2220 \since 5.0
2221
2222 Returns a const \l{STL-style iterators}{STL-style iterator} pointing to the
2223 first character in the string.
2224
2225 \include qstring.cpp iterator-invalidation-func-desc
2226
2227 \sa begin(), cend()
2228*/
2229
2230/*! \fn QString::const_iterator QString::constBegin() const
2231
2232 Returns a const \l{STL-style iterators}{STL-style iterator} pointing to the
2233 first character in the string.
2234
2235 \include qstring.cpp iterator-invalidation-func-desc
2236
2237 \sa begin(), constEnd()
2238*/
2239
2240/*! \fn QString::iterator QString::end()
2241
2242 Returns an \l{STL-style iterators}{STL-style iterator} pointing just after
2243 the last character in the string.
2244
2245 \include qstring.cpp iterator-invalidation-func-desc
2246
2247 \sa begin(), constEnd()
2248*/
2249
2250/*! \fn QString::const_iterator QString::end() const
2251
2252 \overload end()
2253*/
2254
2255/*! \fn QString::const_iterator QString::cend() const
2256 \since 5.0
2257
2258 Returns a const \l{STL-style iterators}{STL-style iterator} pointing just
2259 after the last character in the string.
2260
2261 \include qstring.cpp iterator-invalidation-func-desc
2262
2263 \sa cbegin(), end()
2264*/
2265
2266/*! \fn QString::const_iterator QString::constEnd() const
2267
2268 Returns a const \l{STL-style iterators}{STL-style iterator} pointing just
2269 after the last character in the string.
2270
2271 \include qstring.cpp iterator-invalidation-func-desc
2272
2273 \sa constBegin(), end()
2274*/
2275
2276/*! \fn QString::reverse_iterator QString::rbegin()
2277 \since 5.6
2278
2279 Returns a \l{STL-style iterators}{STL-style} reverse iterator pointing to
2280 the first character in the string, in reverse order.
2281
2282 \include qstring.cpp iterator-invalidation-func-desc
2283
2284 \sa begin(), crbegin(), rend()
2285*/
2286
2287/*! \fn QString::const_reverse_iterator QString::rbegin() const
2288 \since 5.6
2289 \overload
2290*/
2291
2292/*! \fn QString::const_reverse_iterator QString::crbegin() const
2293 \since 5.6
2294
2295 Returns a const \l{STL-style iterators}{STL-style} reverse iterator
2296 pointing to the first character in the string, in reverse order.
2297
2298 \include qstring.cpp iterator-invalidation-func-desc
2299
2300 \sa begin(), rbegin(), rend()
2301*/
2302
2303/*! \fn QString::reverse_iterator QString::rend()
2304 \since 5.6
2305
2306 Returns a \l{STL-style iterators}{STL-style} reverse iterator pointing just
2307 after the last character in the string, in reverse order.
2308
2309 \include qstring.cpp iterator-invalidation-func-desc
2310
2311 \sa end(), crend(), rbegin()
2312*/
2313
2314/*! \fn QString::const_reverse_iterator QString::rend() const
2315 \since 5.6
2316 \overload
2317*/
2318
2319/*! \fn QString::const_reverse_iterator QString::crend() const
2320 \since 5.6
2321
2322 Returns a const \l{STL-style iterators}{STL-style} reverse iterator
2323 pointing just after the last character in the string, in reverse order.
2324
2325 \include qstring.cpp iterator-invalidation-func-desc
2326
2327 \sa end(), rend(), rbegin()
2328*/
2329
2330/*!
2331 \fn QString::QString()
2332
2333 Constructs a null string. Null strings are also considered empty.
2334
2335 \sa isEmpty(), isNull(), {Distinction Between Null and Empty Strings}
2336*/
2337
2338/*!
2339 \fn QString::QString(QString &&other)
2340
2341 Move-constructs a QString instance, making it point at the same
2342 object that \a other was pointing to.
2343
2344 \since 5.2
2345*/
2346
2347/*! \fn QString::QString(const char *str)
2348
2349 Constructs a string initialized with the 8-bit string \a str. The
2350 given const char pointer is converted to Unicode using the
2351 fromUtf8() function.
2352
2353 You can disable this constructor by defining
2354 \l QT_NO_CAST_FROM_ASCII when you compile your applications. This
2355 can be useful if you want to ensure that all user-visible strings
2356 go through QObject::tr(), for example.
2357
2358 \note Defining \l QT_RESTRICTED_CAST_FROM_ASCII also disables
2359 this constructor, but enables a \c{QString(const char (&ch)[N])}
2360 constructor instead. Using non-literal input, or input with
2361 embedded NUL characters, or non-7-bit characters is undefined
2362 in this case.
2363
2364 \sa fromLatin1(), fromLocal8Bit(), fromUtf8()
2365*/
2366
2367/*! \fn QString::QString(const char8_t *str)
2368
2369 Constructs a string initialized with the UTF-8 string \a str. The
2370 given const char8_t pointer is converted to Unicode using the
2371 fromUtf8() function.
2372
2373 \since 6.1
2374 \sa fromLatin1(), fromLocal8Bit(), fromUtf8()
2375*/
2376
2377/*!
2378 \fn QString::QString(QStringView sv)
2379
2380 Constructs a string initialized with the string view's data.
2381
2382 The QString will be null if and only if \a sv is null.
2383
2384 \since 6.8
2385
2386 \sa fromUtf16()
2387*/
2388
2389/*
2390//! [from-std-string]
2391Returns a copy of the \a str string. The given string is assumed to be
2392encoded in \1, and is converted to QString using the \2 function.
2393//! [from-std-string]
2394*/
2395
2396/*! \fn QString QString::fromStdString(const std::string &str)
2397
2398 \include qstring.cpp {from-std-string} {UTF-8} {fromUtf8()}
2399
2400 \sa fromLatin1(), fromLocal8Bit(), fromUtf8(), QByteArray::fromStdString()
2401*/
2402
2403/*! \fn QString QString::fromStdWString(const std::wstring &str)
2404
2405 Returns a copy of the \a str string. The given string is assumed
2406 to be encoded in utf16 if the size of wchar_t is 2 bytes (e.g. on
2407 windows) and ucs4 if the size of wchar_t is 4 bytes (most Unix
2408 systems).
2409
2410 \sa fromUtf16(), fromLatin1(), fromLocal8Bit(), fromUtf8(), fromUcs4(),
2411 fromStdU16String(), fromStdU32String()
2412*/
2413
2414/*! \fn QString QString::fromWCharArray(const wchar_t *string, qsizetype size)
2415 \since 4.2
2416
2417 Reads the first \a size code units of the \c wchar_t array to whose start
2418 \a string points, converting them to Unicode and returning the result as
2419 a QString. The encoding used by \c wchar_t is assumed to be UTF-32 if the
2420 type's size is four bytes or UTF-16 if its size is two bytes.
2421
2422 If \a size is -1 (default), the \a string must be '\\0'-terminated.
2423
2424 \sa fromUtf16(), fromLatin1(), fromLocal8Bit(), fromUtf8(), fromUcs4(),
2425 fromStdWString()
2426*/
2427
2428/*! \fn std::wstring QString::toStdWString() const
2429
2430 Returns a std::wstring object with the data contained in this
2431 QString. The std::wstring is encoded in UTF-16 on platforms where
2432 wchar_t is 2 bytes wide (for example, Windows) and in UTF-32 on platforms
2433 where wchar_t is 4 bytes wide (most Unix systems).
2434
2435 This method is mostly useful to pass a QString to a function
2436 that accepts a std::wstring object.
2437
2438 \sa utf16(), toLatin1(), toUtf8(), toLocal8Bit(), toStdU16String(),
2439 toStdU32String()
2440*/
2441
2442qsizetype QString::toUcs4_helper(const char16_t *uc, qsizetype length, char32_t *out)
2443{
2444 qsizetype count = 0;
2445
2446 QStringIterator i(QStringView(uc, length));
2447 while (i.hasNext())
2448 out[count++] = i.next();
2449
2450 return count;
2451}
2452
2453/*! \fn qsizetype QString::toWCharArray(wchar_t *array) const
2454 \since 4.2
2455
2456 Fills the \a array with the data contained in this QString object.
2457 The array is encoded in UTF-16 on platforms where
2458 wchar_t is 2 bytes wide (e.g. windows) and in UTF-32 on platforms
2459 where wchar_t is 4 bytes wide (most Unix systems).
2460
2461 \a array has to be allocated by the caller and contain enough space to
2462 hold the complete string (allocating the array with the same length as the
2463 string is always sufficient).
2464
2465 This function returns the actual length of the string in \a array.
2466
2467 \note This function does not append a null character to the array.
2468
2469 \sa utf16(), toUcs4(), toLatin1(), toUtf8(), toLocal8Bit(), toStdWString(),
2470 QStringView::toWCharArray()
2471*/
2472
2473/*! \fn QString::QString(const QString &other)
2474
2475 Constructs a copy of \a other.
2476
2477 This operation takes \l{constant time}, because QString is
2478 \l{implicitly shared}. This makes returning a QString from a
2479 function very fast. If a shared instance is modified, it will be
2480 copied (copy-on-write), and that takes \l{linear time}.
2481
2482 \sa operator=()
2483*/
2484
2485/*!
2486 Constructs a string initialized with the first \a size characters
2487 of the QChar array \a unicode.
2488
2489 If \a unicode is 0, a null string is constructed.
2490
2491 If \a size is negative, \a unicode is assumed to point to a '\\0'-terminated
2492 array and its length is determined dynamically. The terminating
2493 null character is not considered part of the string.
2494
2495 QString makes a deep copy of the string data. The unicode data is copied as
2496 is and the Byte Order Mark is preserved if present.
2497
2498 \sa fromRawData()
2499*/
2500QString::QString(const QChar *unicode, qsizetype size)
2501{
2502 if (!unicode) {
2503 d.clear();
2504 } else {
2505 if (size < 0)
2506 size = QtPrivate::qustrlen(reinterpret_cast<const char16_t *>(unicode));
2507 if (!size) {
2508 d = DataPointer::fromRawData(&_empty, 0);
2509 } else {
2510 d = DataPointer(size, size);
2511 Q_CHECK_PTR(d.data());
2512 memcpy(d.data(), unicode, size * sizeof(QChar));
2513 d.data()[size] = '\0';
2514 }
2515 }
2516}
2517
2518/*!
2519 Constructs a string of the given \a size with every character set
2520 to \a ch.
2521
2522 \sa fill()
2523*/
2524QString::QString(qsizetype size, QChar ch)
2525{
2526 if (size <= 0) {
2527 d = DataPointer::fromRawData(&_empty, 0);
2528 } else {
2529 d = DataPointer(size, size);
2530 Q_CHECK_PTR(d.data());
2531 d.data()[size] = '\0';
2532 char16_t *b = d.data();
2533 char16_t *e = d.data() + size;
2534 const char16_t value = ch.unicode();
2535 std::fill(b, e, value);
2536 }
2537}
2538
2539/*! \fn QString::QString(qsizetype size, Qt::Initialization)
2540 \internal
2541
2542 Constructs a string of the given \a size without initializing the
2543 characters. This is only used in \c QStringBuilder::toString().
2544*/
2545QString::QString(qsizetype size, Qt::Initialization)
2546{
2547 if (size <= 0) {
2548 d = DataPointer::fromRawData(&_empty, 0);
2549 } else {
2550 d = DataPointer(size, size);
2551 Q_CHECK_PTR(d.data());
2552 d.data()[size] = '\0';
2553 }
2554}
2555
2556/*! \fn QString::QString(QLatin1StringView str)
2557
2558 Constructs a copy of the Latin-1 string viewed by \a str.
2559
2560 \sa fromLatin1()
2561*/
2562
2563/*!
2564 Constructs a string of size 1 containing the character \a ch.
2565*/
2566QString::QString(QChar ch)
2567{
2568 d = DataPointer(1, 1);
2569 Q_CHECK_PTR(d.data());
2570 d.data()[0] = ch.unicode();
2571 d.data()[1] = '\0';
2572}
2573
2574/*! \fn QString::QString(const QByteArray &ba)
2575
2576 Constructs a string initialized with the byte array \a ba. The
2577 given byte array is converted to Unicode using fromUtf8().
2578
2579 You can disable this constructor by defining
2580 \l QT_NO_CAST_FROM_ASCII when you compile your applications. This
2581 can be useful if you want to ensure that all user-visible strings
2582 go through QObject::tr(), for example.
2583
2584 \note Any null ('\\0') bytes in the byte array will be included in this
2585 string, converted to Unicode null characters (U+0000). This behavior is
2586 different from Qt 5.x.
2587
2588 \sa fromLatin1(), fromLocal8Bit(), fromUtf8()
2589*/
2590
2591/*! \fn QString::QString(const Null &)
2592 \internal
2593*/
2594
2595/*! \fn QString::QString(QStringPrivate)
2596 \internal
2597*/
2598
2599/*! \fn QString &QString::operator=(const QString::Null &)
2600 \internal
2601*/
2602
2603/*!
2604 \fn QString::~QString()
2605
2606 Destroys the string.
2607*/
2608
2609
2610/*! \fn void QString::swap(QString &other)
2611 \since 4.8
2612 \memberswap{string}
2613*/
2614
2615/*! \fn void QString::detach()
2616
2617 Ensures that this string's data is no longer
2618 \l{Implicit Sharing}{shared} with other instances.
2619*/
2620
2621/*! \fn bool QString::isDetached() const
2622
2623 \internal
2624*/
2625
2626/*! \fn bool QString::isSharedWith(const QString &other) const
2627
2628 \internal
2629*/
2630
2631/*! \fn QString::operator std::u16string_view() const
2632 \target qstring-operator-std-u16string_view
2633 \since 6.7
2634
2635 Converts this QString object to a \c{std::u16string_view} object.
2636*/
2637
2638static bool needsReallocate(const QString &str, qsizetype newSize)
2639{
2640 const auto capacityAtEnd = str.capacity() - str.data_ptr().freeSpaceAtBegin();
2641 return newSize > capacityAtEnd;
2642}
2643
2644/*!
2645 Sets the size of the string to \a size characters.
2646
2647 If \a size is greater than the current size, the string is
2648 extended to make it \a size characters long with the extra
2649 characters added to the end. The new characters are uninitialized.
2650
2651 If \a size is less than the current size, characters beyond position
2652 \a size are excluded from the string.
2653
2654 If \a size is negative, it is equivalent to passing zero.
2655
2656 \note While resize() will grow the capacity if needed, it never shrinks
2657 capacity. To shed excess capacity, use squeeze().
2658
2659 Example:
2660
2661 \snippet qstring/main.cpp 45
2662
2663 If you want to append a certain number of identical characters to
2664 the string, use the \l {QString::}{resize(qsizetype, QChar)} overload.
2665
2666 If you want to expand the string so that it reaches a certain
2667 width and fill the new positions with a particular character, use
2668 the leftJustified() function:
2669
2670 \snippet qstring/main.cpp 47
2671
2672 \sa truncate(), reserve(), squeeze()
2673*/
2674
2675void QString::resize(qsizetype size)
2676{
2677 if (size < 0)
2678 size = 0;
2679
2680 if (d.needsDetach() || needsReallocate(*this, size))
2681 reallocData(size, QArrayData::Grow);
2682 d.size = size;
2683 if (d.isMutable())
2684 d.data()[size] = u'\0';
2685}
2686
2687/*!
2688 \overload
2689 \since 5.7
2690
2691 Unlike \l {QString::}{resize(qsizetype)}, this overload
2692 initializes the new characters to \a fillChar:
2693
2694 \snippet qstring/main.cpp 46
2695*/
2696
2697void QString::resize(qsizetype newSize, QChar fillChar)
2698{
2699 const qsizetype oldSize = size();
2700 resize(newSize);
2701 const qsizetype difference = size() - oldSize;
2702 if (difference > 0)
2703 std::fill_n(d.data() + oldSize, difference, fillChar.unicode());
2704}
2705
2706
2707/*!
2708 \since 6.8
2709
2710 Sets the size of the string to \a size characters. If the size of
2711 the string grows, the new characters are uninitialized.
2712
2713 The behavior is identical to \c{resize(size)}.
2714
2715 \sa resize()
2716*/
2717
2718void QString::resizeForOverwrite(qsizetype size)
2719{
2720 resize(size);
2721}
2722
2723
2724/*! \fn qsizetype QString::capacity() const
2725
2726 Returns the maximum number of characters that can be stored in
2727 the string without forcing a reallocation.
2728
2729 The sole purpose of this function is to provide a means of fine
2730 tuning QString's memory usage. In general, you will rarely ever
2731 need to call this function. If you want to know how many
2732 characters are in the string, call size().
2733
2734 \note a statically allocated string will report a capacity of 0,
2735 even if it's not empty.
2736
2737 \note The free space position in the allocated memory block is undefined. In
2738 other words, one should not assume that the free memory is always located
2739 after the initialized elements.
2740
2741 \sa reserve(), squeeze()
2742*/
2743
2744/*!
2745 \fn void QString::reserve(qsizetype size)
2746
2747 Ensures the string has space for at least \a size characters.
2748
2749 If you know in advance how large a string will be, you can call this
2750 function to save repeated reallocation while building it.
2751 This can improve performance when building a string incrementally.
2752 A long sequence of operations that add to a string may trigger several
2753 reallocations, the last of which may leave you with significantly more
2754 space than you need. This is less efficient than doing a single
2755 allocation of the right size at the start.
2756
2757 If in doubt about how much space shall be needed, it is usually better to
2758 use an upper bound as \a size, or a high estimate of the most likely size,
2759 if a strict upper bound would be much bigger than this. If \a size is an
2760 underestimate, the string will grow as needed once the reserved size is
2761 exceeded, which may lead to a larger allocation than your best
2762 overestimate would have and will slow the operation that triggers it.
2763
2764 \warning reserve() reserves memory but does not change the size of the
2765 string. Accessing data beyond the end of the string is undefined behavior.
2766 If you need to access memory beyond the current end of the string,
2767 use resize().
2768
2769 This function is useful for code that needs to build up a long
2770 string and wants to avoid repeated reallocation. In this example,
2771 we want to add to the string until some condition is \c true, and
2772 we're fairly sure that size is large enough to make a call to
2773 reserve() worthwhile:
2774
2775 \snippet qstring/main.cpp 44
2776
2777 \sa squeeze(), capacity(), resize()
2778*/
2779
2780/*!
2781 \fn void QString::squeeze()
2782
2783 Releases any memory not required to store the character data.
2784
2785 The sole purpose of this function is to provide a means of fine
2786 tuning QString's memory usage. In general, you will rarely ever
2787 need to call this function.
2788
2789 \sa reserve(), capacity()
2790*/
2791
2792void QString::reallocData(qsizetype alloc, QArrayData::AllocationOption option)
2793{
2794 if (!alloc) {
2795 d = DataPointer::fromRawData(&_empty, 0);
2796 return;
2797 }
2798
2799 // don't use reallocate path when reducing capacity and there's free space
2800 // at the beginning: might shift data pointer outside of allocated space
2801 const bool cannotUseReallocate = d.freeSpaceAtBegin() > 0;
2802
2803 if (d.needsDetach() || cannotUseReallocate) {
2804 DataPointer dd(alloc, qMin(alloc, d.size), option);
2805 Q_CHECK_PTR(dd.data());
2806 if (dd.size > 0)
2807 ::memcpy(dd.data(), d.data(), dd.size * sizeof(QChar));
2808 dd.data()[dd.size] = 0;
2809 d.swap(dd);
2810 } else {
2811 d->reallocate(alloc, option);
2812 }
2813}
2814
2815void QString::reallocGrowData(qsizetype n)
2816{
2817 if (!n) // expected to always allocate
2818 n = 1;
2819
2820 if (d.needsDetach()) {
2821 DataPointer dd(DataPointer::allocateGrow(d, n, QArrayData::GrowsAtEnd));
2822 Q_CHECK_PTR(dd.data());
2823 dd->copyAppend(d.data(), d.data() + d.size);
2824 dd.data()[dd.size] = 0;
2825 d.swap(dd);
2826 } else {
2827 d->reallocate(d.constAllocatedCapacity() + n, QArrayData::Grow);
2828 }
2829}
2830
2831/*! \fn void QString::clear()
2832
2833 Clears the contents of the string and makes it null.
2834
2835 \sa resize(), isNull()
2836*/
2837
2838/*! \fn QString &QString::operator=(const QString &other)
2839
2840 Assigns \a other to this string and returns a reference to this
2841 string.
2842*/
2843
2844/*!
2845 \fn QString &QString::operator=(QString &&other)
2846
2847 Move-assigns \a other to this QString instance.
2848
2849 \since 5.2
2850*/
2851
2852/*! \fn QString &QString::operator=(QLatin1StringView str)
2853
2854 \overload operator=()
2855
2856 Assigns the Latin-1 string viewed by \a str to this string.
2857*/
2858QString &QString::operator=(QLatin1StringView other)
2859{
2860 const qsizetype capacityAtEnd = capacity() - d.freeSpaceAtBegin();
2861 if (isDetached() && other.size() <= capacityAtEnd) { // assumes d.alloc == 0 -> !isDetached() (sharedNull)
2862 d.size = other.size();
2863 d.data()[other.size()] = 0;
2864 qt_from_latin1(d.data(), other.latin1(), other.size());
2865 } else {
2866 *this = fromLatin1(other.latin1(), other.size());
2867 }
2868 return *this;
2869}
2870
2871/*! \fn QString &QString::operator=(const QByteArray &ba)
2872
2873 \overload operator=()
2874
2875 Assigns \a ba to this string. The byte array is converted to Unicode
2876 using the fromUtf8() function.
2877
2878 You can disable this operator by defining
2879 \l QT_NO_CAST_FROM_ASCII when you compile your applications. This
2880 can be useful if you want to ensure that all user-visible strings
2881 go through QObject::tr(), for example.
2882*/
2883
2884/*! \fn QString &QString::operator=(const char *str)
2885
2886 \overload operator=()
2887
2888 Assigns \a str to this string. The const char pointer is converted
2889 to Unicode using the fromUtf8() function.
2890
2891 You can disable this operator by defining \l QT_NO_CAST_FROM_ASCII
2892 or \l QT_RESTRICTED_CAST_FROM_ASCII when you compile your applications.
2893 This can be useful if you want to ensure that all user-visible strings
2894 go through QObject::tr(), for example.
2895*/
2896
2897/*!
2898 \overload operator=()
2899
2900 Sets the string to contain the single character \a ch.
2901*/
2902QString &QString::operator=(QChar ch)
2903{
2904 return assign(1, ch);
2905}
2906
2907/*!
2908 \fn QString& QString::insert(qsizetype position, const QString &str)
2909
2910 Inserts the string \a str at the given index \a position and
2911 returns a reference to this string.
2912
2913 Example:
2914
2915 \snippet qstring/main.cpp 26
2916
2917//! [string-grow-at-insertion]
2918 This string grows to accommodate the insertion. If \a position is beyond
2919 the end of the string, space characters are appended to the string to reach
2920 this \a position, followed by \a str.
2921//! [string-grow-at-insertion]
2922
2923 \sa append(), prepend(), replace(), remove()
2924*/
2925
2926/*!
2927 \fn QString& QString::insert(qsizetype position, QStringView str)
2928 \since 6.0
2929 \overload insert()
2930
2931 Inserts the string view \a str at the given index \a position and
2932 returns a reference to this string.
2933
2934 \include qstring.cpp string-grow-at-insertion
2935*/
2936
2937
2938/*!
2939 \fn QString& QString::insert(qsizetype position, const char *str)
2940 \since 5.5
2941 \overload insert()
2942
2943 Inserts the C string \a str at the given index \a position and
2944 returns a reference to this string.
2945
2946 \include qstring.cpp string-grow-at-insertion
2947
2948 This function is not available when \l QT_NO_CAST_FROM_ASCII is
2949 defined.
2950*/
2951
2952/*!
2953 \fn QString& QString::insert(qsizetype position, const QByteArray &str)
2954 \since 5.5
2955 \overload insert()
2956
2957 Interprets the contents of \a str as UTF-8, inserts the Unicode string
2958 it encodes at the given index \a position and returns a reference to
2959 this string.
2960
2961 \include qstring.cpp string-grow-at-insertion
2962
2963 This function is not available when \l QT_NO_CAST_FROM_ASCII is
2964 defined.
2965*/
2966
2967/*! \internal
2968 T is a view or a container on/of QChar, char16_t, or char
2969*/
2970template <typename T>
2971static void insert_helper(QString &str, qsizetype i, const T &toInsert)
2972{
2973 auto &str_d = str.data_ptr();
2974 qsizetype difference = 0;
2975 if (Q_UNLIKELY(i > str_d.size))
2976 difference = i - str_d.size;
2977 const qsizetype oldSize = str_d.size;
2978 const qsizetype insert_size = toInsert.size();
2979 const qsizetype newSize = str_d.size + difference + insert_size;
2980 const auto side = i == 0 ? QArrayData::GrowsAtBeginning : QArrayData::GrowsAtEnd;
2981
2982 if (str_d.needsDetach() || needsReallocate(str, newSize)) {
2983 const auto cbegin = str.cbegin();
2984 const auto cend = str.cend();
2985 const auto insert_start = difference == 0 ? std::next(cbegin, i) : cend;
2986 QString other;
2987 // Using detachAndGrow() so that prepend optimization works and QStringBuilder
2988 // unittests pass
2989 other.data_ptr().detachAndGrow(side, newSize, nullptr, nullptr);
2990 other.append(QStringView(cbegin, insert_start));
2991 other.resize(i, u' ');
2992 other.append(toInsert);
2993 other.append(QStringView(insert_start, cend));
2994 str.swap(other);
2995 return;
2996 }
2997
2998 str_d.detachAndGrow(side, difference + insert_size, nullptr, nullptr);
2999 Q_CHECK_PTR(str_d.data());
3000 str.resize(newSize);
3001
3002 auto begin = str_d.begin();
3003 auto old_end = std::next(begin, oldSize);
3004 std::fill_n(old_end, difference, u' ');
3005 auto insert_start = std::next(begin, i);
3006 if (difference == 0)
3007 std::move_backward(insert_start, old_end, str_d.end());
3008
3009 using Char = std::remove_cv_t<typename T::value_type>;
3010 if constexpr(std::is_same_v<Char, QChar>)
3011 std::copy_n(reinterpret_cast<const char16_t *>(toInsert.data()), insert_size, insert_start);
3012 else if constexpr (std::is_same_v<Char, char16_t>)
3013 std::copy_n(toInsert.data(), insert_size, insert_start);
3014 else if constexpr (std::is_same_v<Char, char>)
3015 qt_from_latin1(insert_start, toInsert.data(), insert_size);
3016}
3017
3018/*!
3019 \fn QString &QString::insert(qsizetype position, QLatin1StringView str)
3020 \overload insert()
3021
3022 Inserts the Latin-1 string viewed by \a str at the given index \a position.
3023
3024 \include qstring.cpp string-grow-at-insertion
3025*/
3026QString &QString::insert(qsizetype i, QLatin1StringView str)
3027{
3028 if (i < 0 || str.isEmpty())
3029 return *this;
3030
3031 insert_helper(*this, i, str);
3032 return *this;
3033}
3034
3035/*!
3036 \fn QString &QString::insert(qsizetype position, QUtf8StringView str)
3037 \overload insert()
3038 \since 6.5
3039
3040 Inserts the UTF-8 string view \a str at the given index \a position.
3041
3042 \note Inserting variable-width UTF-8-encoded string data is conceptually slower
3043 than inserting fixed-width string data such as UTF-16 (QStringView) or Latin-1
3044 (QLatin1StringView) and should thus be used sparingly.
3045
3046 \include qstring.cpp string-grow-at-insertion
3047*/
3048QString &QString::insert(qsizetype i, QUtf8StringView s)
3049{
3050 auto insert_size = s.size();
3051 if (i < 0 || insert_size <= 0)
3052 return *this;
3053
3054 qsizetype difference = 0;
3055 if (Q_UNLIKELY(i > d.size))
3056 difference = i - d.size;
3057
3058 const qsizetype newSize = d.size + difference + insert_size;
3059
3060 if (d.needsDetach() || needsReallocate(*this, newSize)) {
3061 const auto cbegin = this->cbegin();
3062 const auto insert_start = difference == 0 ? std::next(cbegin, i) : cend();
3063 QString other;
3064 other.reserve(newSize);
3065 other.append(QStringView(cbegin, insert_start));
3066 if (difference > 0)
3067 other.resize(i, u' ');
3068 other.append(s);
3069 other.append(QStringView(insert_start, cend()));
3070 swap(other);
3071 return *this;
3072 }
3073
3074 if (i >= d.size) {
3075 d.detachAndGrow(QArrayData::GrowsAtEnd, difference + insert_size, nullptr, nullptr);
3076 Q_CHECK_PTR(d.data());
3077
3078 if (difference > 0)
3079 resize(i, u' ');
3080 append(s);
3081 } else {
3082 // Optimal insertion of Utf8 data is at the end, anywhere else could
3083 // potentially lead to moving characters twice if Utf8 data size
3084 // (variable-width) is less than the equivalent Utf16 data size
3085 QVarLengthArray<char16_t> buffer(insert_size); // ### optimize (QTBUG-108546)
3086 char16_t *b = QUtf8::convertToUnicode(buffer.data(), s);
3087 insert_helper(*this, i, QStringView(buffer.data(), b));
3088 }
3089
3090 return *this;
3091}
3092
3093/*!
3094 \fn QString& QString::insert(qsizetype position, const QChar *unicode, qsizetype size)
3095 \overload insert()
3096
3097 Inserts the first \a size characters of the QChar array \a unicode
3098 at the given index \a position in the string.
3099
3100 This string grows to accommodate the insertion. If \a position is beyond
3101 the end of the string, space characters are appended to the string to reach
3102 this \a position, followed by \a size characters of the QChar array
3103 \a unicode.
3104*/
3105QString& QString::insert(qsizetype i, const QChar *unicode, qsizetype size)
3106{
3107 if (i < 0 || size <= 0)
3108 return *this;
3109
3110 // In case when data points into "this"
3111 if (!d.needsDetach() && QtPrivate::q_points_into_range(unicode, *this)) {
3112 QVarLengthArray copy(unicode, unicode + size);
3113 insert(i, copy.data(), size);
3114 } else {
3115 insert_helper(*this, i, QStringView(unicode, size));
3116 }
3117
3118 return *this;
3119}
3120
3121/*!
3122 \fn QString& QString::insert(qsizetype position, QChar ch)
3123 \overload insert()
3124
3125 Inserts \a ch at the given index \a position in the string.
3126
3127 This string grows to accommodate the insertion. If \a position is beyond
3128 the end of the string, space characters are appended to the string to reach
3129 this \a position, followed by \a ch.
3130*/
3131
3132QString& QString::insert(qsizetype i, QChar ch)
3133{
3134 if (i < 0)
3135 i += d.size;
3136 return insert(i, &ch, 1);
3137}
3138
3139/*!
3140 Appends the string \a str onto the end of this string.
3141
3142 Example:
3143
3144 \snippet qstring/main.cpp 9
3145
3146 This is the same as using the insert() function:
3147
3148 \snippet qstring/main.cpp 10
3149
3150 The append() function is typically very fast (\l{constant time}),
3151 because QString preallocates extra space at the end of the string
3152 data so it can grow without reallocating the entire string each
3153 time.
3154
3155 \sa operator+=(), prepend(), insert()
3156*/
3157QString &QString::append(const QString &str)
3158{
3159 if (!str.isNull()) {
3160 if (isNull()) {
3161 if (Q_UNLIKELY(!str.d.isMutable()))
3162 assign(str); // fromRawData, so we do a deep copy
3163 else
3164 operator=(str);
3165 } else if (str.size()) {
3166 append(str.constData(), str.size());
3167 }
3168 }
3169 return *this;
3170}
3171
3172/*!
3173 \fn QString &QString::append(QStringView v)
3174 \overload append()
3175 \since 6.0
3176
3177 Appends the given string view \a v to this string and returns the result.
3178*/
3179
3180/*!
3181 \overload append()
3182 \since 5.0
3183
3184 Appends \a len characters from the QChar array \a str to this string.
3185*/
3186QString &QString::append(const QChar *str, qsizetype len)
3187{
3188 if (str && len > 0) {
3189 static_assert(sizeof(QChar) == sizeof(char16_t), "Unexpected difference in sizes");
3190 // the following should be safe as QChar uses char16_t as underlying data
3191 const char16_t *char16String = reinterpret_cast<const char16_t *>(str);
3192 d->growAppend(char16String, char16String + len);
3193 d.data()[d.size] = u'\0';
3194 }
3195 return *this;
3196}
3197
3198/*!
3199 \overload append()
3200
3201 Appends the Latin-1 string viewed by \a str to this string.
3202*/
3203QString &QString::append(QLatin1StringView str)
3204{
3205 append_helper(*this, str);
3206 return *this;
3207}
3208
3209/*!
3210 \overload append()
3211 \since 6.5
3212
3213 Appends the UTF-8 string view \a str to this string.
3214*/
3215QString &QString::append(QUtf8StringView str)
3216{
3217 append_helper(*this, str);
3218 return *this;
3219}
3220
3221/*! \fn QString &QString::append(const QByteArray &ba)
3222
3223 \overload append()
3224
3225 Appends the byte array \a ba to this string. The given byte array
3226 is converted to Unicode using the fromUtf8() function.
3227
3228 You can disable this function by defining \l QT_NO_CAST_FROM_ASCII
3229 when you compile your applications. This can be useful if you want
3230 to ensure that all user-visible strings go through QObject::tr(),
3231 for example.
3232*/
3233
3234/*! \fn QString &QString::append(const char *str)
3235
3236 \overload append()
3237
3238 Appends the string \a str to this string. The given const char
3239 pointer is converted to Unicode using the fromUtf8() function.
3240
3241 You can disable this function by defining \l QT_NO_CAST_FROM_ASCII
3242 when you compile your applications. This can be useful if you want
3243 to ensure that all user-visible strings go through QObject::tr(),
3244 for example.
3245*/
3246
3247/*!
3248 \overload append()
3249
3250 Appends the character \a ch to this string.
3251*/
3252QString &QString::append(QChar ch)
3253{
3254 d.detachAndGrow(QArrayData::GrowsAtEnd, 1, nullptr, nullptr);
3255 d->copyAppend(1, ch.unicode());
3256 d.data()[d.size] = '\0';
3257 return *this;
3258}
3259
3260/*! \fn QString &QString::prepend(const QString &str)
3261
3262 Prepends the string \a str to the beginning of this string and
3263 returns a reference to this string.
3264
3265 This operation is typically very fast (\l{constant time}), because
3266 QString preallocates extra space at the beginning of the string data,
3267 so it can grow without reallocating the entire string each time.
3268
3269 Example:
3270
3271 \snippet qstring/main.cpp 36
3272
3273 \sa append(), insert()
3274*/
3275
3276/*! \fn QString &QString::prepend(QLatin1StringView str)
3277
3278 \overload prepend()
3279
3280 Prepends the Latin-1 string viewed by \a str to this string.
3281*/
3282
3283/*! \fn QString &QString::prepend(QUtf8StringView str)
3284 \since 6.5
3285 \overload prepend()
3286
3287 Prepends the UTF-8 string view \a str to this string.
3288*/
3289
3290/*! \fn QString &QString::prepend(const QChar *str, qsizetype len)
3291 \since 5.5
3292 \overload prepend()
3293
3294 Prepends \a len characters from the QChar array \a str to this string and
3295 returns a reference to this string.
3296*/
3297
3298/*! \fn QString &QString::prepend(QStringView str)
3299 \since 6.0
3300 \overload prepend()
3301
3302 Prepends the string view \a str to the beginning of this string and
3303 returns a reference to this string.
3304*/
3305
3306/*! \fn QString &QString::prepend(const QByteArray &ba)
3307
3308 \overload prepend()
3309
3310 Prepends the byte array \a ba to this string. The byte array is
3311 converted to Unicode using the fromUtf8() function.
3312
3313 You can disable this function by defining
3314 \l QT_NO_CAST_FROM_ASCII when you compile your applications. This
3315 can be useful if you want to ensure that all user-visible strings
3316 go through QObject::tr(), for example.
3317*/
3318
3319/*! \fn QString &QString::prepend(const char *str)
3320
3321 \overload prepend()
3322
3323 Prepends the string \a str to this string. The const char pointer
3324 is converted to Unicode using the fromUtf8() function.
3325
3326 You can disable this function by defining
3327 \l QT_NO_CAST_FROM_ASCII when you compile your applications. This
3328 can be useful if you want to ensure that all user-visible strings
3329 go through QObject::tr(), for example.
3330*/
3331
3332/*! \fn QString &QString::prepend(QChar ch)
3333
3334 \overload prepend()
3335
3336 Prepends the character \a ch to this string.
3337*/
3338
3339/*!
3340 \fn QString &QString::assign(QAnyStringView v)
3341 \since 6.6
3342
3343 Replaces the contents of this string with a copy of \a v and returns a
3344 reference to this string.
3345
3346 The size of this string will be equal to the size of \a v, converted to
3347 UTF-16 as if by \c{v.toString()}. Unlike QAnyStringView::toString(), however,
3348 this function only allocates memory if the estimated size exceeds the capacity
3349 of this string or this string is shared.
3350
3351 \sa QAnyStringView::toString()
3352*/
3353
3354/*!
3355 \fn QString &QString::assign(qsizetype n, QChar c)
3356 \since 6.6
3357
3358 Replaces the contents of this string with \a n copies of \a c and
3359 returns a reference to this string.
3360
3361 The size of this string will be equal to \a n, which has to be non-negative.
3362
3363 This function will only allocate memory if \a n exceeds the capacity of this
3364 string or this string is shared.
3365
3366 \sa fill()
3367*/
3368
3369/*!
3370 \fn template <typename InputIterator, QString::if_compatible_iterator<InputIterator>> QString &QString::assign(InputIterator first, InputIterator last)
3371 \since 6.6
3372
3373 Replaces the contents of this string with a copy of the elements in the
3374 iterator range [\a first, \a last) and returns a reference to this string.
3375
3376 The size of this string will be equal to the decoded length of the elements
3377 in the range [\a first, \a last), which need not be the same as the length of
3378 the range itself, because this function transparently recodes the input
3379 character set to UTF-16.
3380
3381 This function will only allocate memory if the number of elements in the
3382 range, or, for non-UTF-16-encoded input, the maximum possible size of the
3383 resulting string, exceeds the capacity of this string, or if this string is
3384 shared.
3385
3386 \note The behavior is undefined if either argument is an iterator into *this or
3387 [\a first, \a last) is not a valid range.
3388
3389 \constraints
3390 \c InputIterator meets the requirements of a
3391 \l {https://en.cppreference.com/w/cpp/named_req/InputIterator} {LegacyInputIterator}
3392 and the \c{value_type} of \c InputIterator is one of the following character types:
3393 \list
3394 \li QChar
3395 \li QLatin1Char
3396 \li \c {char}
3397 \li \c {unsigned char}
3398 \li \c {signed char}
3399 \li \c {char8_t}
3400 \li \c char16_t
3401 \li (on platforms, such as Windows, where it is a 16-bit type) \c wchar_t
3402 \li \c char32_t
3403 \endlist
3404*/
3405
3406QString &QString::assign(QAnyStringView s)
3407{
3408 if (s.size() <= capacity() && isDetached()) {
3409 const auto offset = d.freeSpaceAtBegin();
3410 if (offset)
3411 d.setBegin(d.begin() - offset);
3412 resize(0);
3413 s.visit([this](auto input) {
3414 this->append(input);
3415 });
3416 } else {
3417 *this = s.toString();
3418 }
3419 return *this;
3420}
3421
3422#ifndef QT_BOOTSTRAPPED
3423QString &QString::assign_helper(const char32_t *data, qsizetype len)
3424{
3425 Q_ASSERT(len >= 0);
3426 // worst case: each char32_t requires a surrogate pair, so
3427 const auto requiredCapacity = len * 2; // cannot overflow: bounded by memory for [data, len)
3428 if (requiredCapacity <= capacity() && isDetached()) {
3429 const auto offset = d.freeSpaceAtBegin();
3430 if (offset)
3431 d.setBegin(d.begin() - offset);
3432 auto begin = reinterpret_cast<QChar *>(d.begin());
3433 auto ba = QByteArrayView(reinterpret_cast<const std::byte*>(data), len * sizeof(char32_t));
3434 QStringConverter::State state;
3435 const auto end = QUtf32::convertToUnicode(begin, ba, &state, DetectEndianness);
3436 d.size = end - begin;
3437 d.data()[d.size] = u'\0';
3438 } else {
3439 *this = QString::fromUcs4(data, len);
3440 }
3441 return *this;
3442}
3443#endif
3444
3445/*!
3446 \fn QString &QString::remove(qsizetype position, qsizetype n)
3447
3448 Removes \a n characters from the string, starting at the given \a
3449 position index, and returns a reference to the string.
3450
3451 If the specified \a position index is within the string, but \a
3452 position + \a n is beyond the end of the string, the string is
3453 truncated at the specified \a position.
3454
3455 If \a n is <= 0 nothing is changed.
3456
3457 \snippet qstring/main.cpp 37
3458
3459//! [shrinking-erase]
3460 Element removal will preserve the string's capacity and not reduce the
3461 amount of allocated memory. To shed extra capacity and free as much memory
3462 as possible, call squeeze() after the last change to the string's size.
3463//! [shrinking-erase]
3464
3465 \sa insert(), replace()
3466*/
3467QString &QString::remove(qsizetype pos, qsizetype len)
3468{
3469 if (pos < 0) // count from end of string
3470 pos += size();
3471
3472 if (size_t(pos) >= size_t(size()) || len <= 0)
3473 return *this;
3474
3475 len = std::min(len, size() - pos);
3476
3477 if (!d.isShared()) {
3478 d->erase(d.begin() + pos, len);
3479 d.data()[d.size] = u'\0';
3480 } else {
3481 // TODO: either reserve "size()", which is bigger than needed, or
3482 // modify the shrinking-erase docs of this method (since the size
3483 // of "copy" won't have any extra capacity any more)
3484 const qsizetype sz = size() - len;
3485 QString copy{sz, Qt::Uninitialized};
3486 auto begin = d.begin();
3487 auto toRemove_start = d.begin() + pos;
3488 copy.d->copyRanges({{begin, toRemove_start},
3489 {toRemove_start + len, d.end()}});
3490 swap(copy);
3491 }
3492 return *this;
3493}
3494
3495template<typename T>
3496static void removeStringImpl(QString &s, const T &needle, Qt::CaseSensitivity cs)
3497{
3498 const auto needleSize = needle.size();
3499 if (!needleSize)
3500 return;
3501
3502 // avoid detach if nothing to do:
3503 qsizetype i = s.indexOf(needle, 0, cs);
3504 if (i < 0)
3505 return;
3506
3507 QString::DataPointer &dptr = s.data_ptr();
3508 auto begin = dptr.begin();
3509 auto end = dptr.end();
3510
3511 auto copyFunc = [&](auto &dst) {
3512 auto src = begin + i + needleSize;
3513 while (src < end) {
3514 i = s.indexOf(needle, std::distance(begin, src), cs);
3515 auto hit = i == -1 ? end : begin + i;
3516 dst = std::copy(src, hit, dst);
3517 src = hit + needleSize;
3518 }
3519 return dst;
3520 };
3521
3522 if (!dptr.needsDetach()) {
3523 auto dst = begin + i;
3524 dst = copyFunc(dst);
3525 s.truncate(std::distance(begin, dst));
3526 } else {
3527 QString copy{s.size(), Qt::Uninitialized};
3528 auto copy_begin = copy.begin();
3529 auto dst = std::copy(begin, begin + i, copy_begin); // Chunk before the first hit
3530 dst = copyFunc(dst);
3531 copy.resize(std::distance(copy_begin, dst));
3532 s.swap(copy);
3533 }
3534}
3535
3536/*!
3537 Removes every occurrence of the given \a str string in this
3538 string, and returns a reference to this string.
3539
3540 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
3541
3542 This is the same as \c replace(str, "", cs).
3543
3544 \include qstring.cpp shrinking-erase
3545
3546 \sa replace()
3547*/
3548QString &QString::remove(const QString &str, Qt::CaseSensitivity cs)
3549{
3550 const auto s = str.d.data();
3551 if (QtPrivate::q_points_into_range(s, d))
3552 removeStringImpl(*this, QStringView{QVarLengthArray(s, s + str.size())}, cs);
3553 else
3554 removeStringImpl(*this, qToStringViewIgnoringNull(str), cs);
3555 return *this;
3556}
3557
3558/*!
3559 \since 5.11
3560 \overload
3561
3562 Removes every occurrence of the given Latin-1 string viewed by \a str
3563 from this string, and returns a reference to this string.
3564
3565 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
3566
3567 This is the same as \c replace(str, "", cs).
3568
3569 \include qstring.cpp shrinking-erase
3570
3571 \sa replace()
3572*/
3573QString &QString::remove(QLatin1StringView str, Qt::CaseSensitivity cs)
3574{
3575 removeStringImpl(*this, str, cs);
3576 return *this;
3577}
3578
3579/*!
3580 \fn QString &QString::removeAt(qsizetype pos)
3581
3582 \since 6.5
3583
3584 Removes the character at index \a pos. If \a pos is out of bounds
3585 (i.e. \a pos >= size()), this function does nothing.
3586
3587 \sa remove()
3588*/
3589
3590/*!
3591 \fn QString &QString::removeFirst()
3592
3593 \since 6.5
3594
3595 Removes the first character in this string. If the string is empty,
3596 this function does nothing.
3597
3598 \sa remove()
3599*/
3600
3601/*!
3602 \fn QString &QString::removeLast()
3603
3604 \since 6.5
3605
3606 Removes the last character in this string. If the string is empty,
3607 this function does nothing.
3608
3609 \sa remove()
3610*/
3611
3612/*!
3613 Removes every occurrence of the character \a ch in this string, and
3614 returns a reference to this string.
3615
3616 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
3617
3618 Example:
3619
3620 \snippet qstring/main.cpp 38
3621
3622 This is the same as \c replace(ch, "", cs).
3623
3624 \include qstring.cpp shrinking-erase
3625
3626 \sa replace()
3627*/
3628QString &QString::remove(QChar ch, Qt::CaseSensitivity cs)
3629{
3630 const qsizetype idx = indexOf(ch, 0, cs);
3631 if (idx == -1)
3632 return *this;
3633
3634 const bool isCase = cs == Qt::CaseSensitive;
3635 ch = isCase ? ch : ch.toCaseFolded();
3636 auto match = [ch, isCase](QChar x) {
3637 return ch == (isCase ? x : x.toCaseFolded());
3638 };
3639
3640
3641 auto begin = d.begin();
3642 auto first_match = begin + idx;
3643 auto end = d.end();
3644 if (!d.isShared()) {
3645 auto it = std::remove_if(first_match, end, match);
3646 d->erase(it, std::distance(it, end));
3647 d.data()[d.size] = u'\0';
3648 } else {
3649 // Instead of detaching, create a new string and copy all characters except for
3650 // the ones we're removing
3651 // TODO: size() is more than the needed since "copy" would be shorter
3652 QString copy{size(), Qt::Uninitialized};
3653 auto dst = copy.d.begin();
3654 auto it = std::copy(begin, first_match, dst); // Chunk before idx
3655 it = std::remove_copy_if(first_match + 1, end, it, match);
3656 copy.d.size = std::distance(dst, it);
3657 copy.d.data()[copy.d.size] = u'\0';
3658 *this = std::move(copy);
3659 }
3660 return *this;
3661}
3662
3663/*!
3664 \fn QString &QString::remove(const QRegularExpression &re)
3665 \since 5.0
3666
3667 Removes every occurrence of the regular expression \a re in the
3668 string, and returns a reference to the string. For example:
3669
3670 \snippet qstring/main.cpp 96
3671
3672 \include qstring.cpp shrinking-erase
3673
3674 \sa indexOf(), lastIndexOf(), replace()
3675*/
3676
3677/*!
3678 \fn template <typename Predicate> QString &QString::removeIf(Predicate pred)
3679 \since 6.1
3680
3681 Removes all elements for which the predicate \a pred returns true
3682 from the string. Returns a reference to the string.
3683
3684 \sa remove()
3685*/
3686
3687static void replace_helper(QString &str, QSpan<qsizetype> indices, qsizetype blen, QStringView after)
3688{
3689 const qsizetype oldSize = str.data_ptr().size;
3690 const qsizetype adjust = indices.size() * (after.size() - blen);
3691 const qsizetype newSize = oldSize + adjust;
3692 using A = QStringAlgorithms<QString>;
3693 if (str.data_ptr().needsDetach() || needsReallocate(str, newSize)) {
3694 A::replace_helper(str, blen, after, indices);
3695 return;
3696 }
3697
3698 if (QtPrivate::q_points_into_range(after.begin(), str)) {
3699 // Copy after if it lies inside our own d.b area (which we could
3700 // possibly invalidate via a realloc or modify by replacement)
3701 A::replace_helper(str, blen, QVarLengthArray(after.begin(), after.end()), indices);
3702 } else {
3703 A::replace_helper(str, blen, after, indices);
3704 }
3705}
3706
3707/*!
3708 \fn QString &QString::replace(qsizetype position, qsizetype n, const QString &after)
3709
3710 Replaces \a n characters beginning at index \a position with
3711 the string \a after and returns a reference to this string.
3712
3713 \note If the specified \a position index is within the string,
3714 but \a position + \a n goes outside the strings range,
3715 then \a n will be adjusted to stop at the end of the string.
3716
3717 Example:
3718
3719 \snippet qstring/main.cpp 40
3720
3721 \sa insert(), remove()
3722*/
3723QString &QString::replace(qsizetype pos, qsizetype len, const QString &after)
3724{
3725 return replace(pos, len, after.constData(), after.size());
3726}
3727
3728/*!
3729 \fn QString &QString::replace(qsizetype position, qsizetype n, const QChar *after, qsizetype alen)
3730 \overload replace()
3731 Replaces \a n characters beginning at index \a position with the
3732 first \a alen characters of the QChar array \a after and returns a
3733 reference to this string.
3734
3735 \a n must not be negative.
3736*/
3737QString &QString::replace(qsizetype pos, qsizetype len, const QChar *after, qsizetype alen)
3738{
3739 Q_PRE(len >= 0);
3740
3741 if (size_t(pos) > size_t(this->size()))
3742 return *this;
3743 if (len > this->size() - pos)
3744 len = this->size() - pos;
3745
3746 qsizetype indices[] = {pos};
3747 replace_helper(*this, indices, len, QStringView{after, alen});
3748 return *this;
3749}
3750
3751/*!
3752 \fn QString &QString::replace(qsizetype position, qsizetype n, QChar after)
3753 \overload replace()
3754
3755 Replaces \a n characters beginning at index \a position with the
3756 character \a after and returns a reference to this string.
3757*/
3758QString &QString::replace(qsizetype pos, qsizetype len, QChar after)
3759{
3760 return replace(pos, len, &after, 1);
3761}
3762
3763/*!
3764 \overload replace()
3765 Replaces every occurrence of the string \a before with the string \a
3766 after and returns a reference to this string.
3767
3768 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
3769
3770 Example:
3771
3772 \snippet qstring/main.cpp 41
3773
3774 \note The replacement text is not rescanned after it is inserted.
3775
3776 Example:
3777
3778 \snippet qstring/main.cpp 86
3779
3780//! [empty-before-arg-in-replace]
3781 \note If you use an empty \a before argument, the \a after argument will be
3782 inserted \e {before and after} each character of the string.
3783//! [empty-before-arg-in-replace]
3784
3785*/
3786QString &QString::replace(const QString &before, const QString &after, Qt::CaseSensitivity cs)
3787{
3788 return replace(before.constData(), before.size(), after.constData(), after.size(), cs);
3789}
3790
3791/*!
3792 \since 4.5
3793 \overload replace()
3794
3795 Replaces each occurrence in this string of the first \a blen
3796 characters of \a before with the first \a alen characters of \a
3797 after and returns a reference to this string.
3798
3799 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
3800
3801 \note If \a before points to an \e empty string (that is, \a blen == 0),
3802 the string pointed to by \a after will be inserted \e {before and after}
3803 each character in this string.
3804*/
3805QString &QString::replace(const QChar *before, qsizetype blen,
3806 const QChar *after, qsizetype alen,
3807 Qt::CaseSensitivity cs)
3808{
3809 if (isEmpty()) {
3810 if (blen)
3811 return *this;
3812 } else {
3813 if (cs == Qt::CaseSensitive && before == after && blen == alen)
3814 return *this;
3815 }
3816 if (alen == 0 && blen == 0)
3817 return *this;
3818 if (alen == 1 && blen == 1)
3819 return replace(*before, *after, cs);
3820
3821 QStringMatcher matcher(before, blen, cs);
3822
3823 qsizetype index = 0;
3824
3825 QVarLengthArray<qsizetype> indices;
3826 while ((index = matcher.indexIn(*this, index)) != -1) {
3827 indices.push_back(index);
3828 if (blen) // Step over before:
3829 index += blen;
3830 else // Only count one instance of empty between any two characters:
3831 index++;
3832 }
3833 if (indices.isEmpty())
3834 return *this;
3835
3836 replace_helper(*this, indices, blen, QStringView{after, alen});
3837 return *this;
3838}
3839
3840/*!
3841 \overload replace()
3842 Replaces every occurrence of the character \a ch in the string with
3843 \a after and returns a reference to this string.
3844
3845 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
3846*/
3847QString& QString::replace(QChar ch, const QString &after, Qt::CaseSensitivity cs)
3848{
3849 if (after.size() == 0)
3850 return remove(ch, cs);
3851
3852 if (after.size() == 1)
3853 return replace(ch, after.front(), cs);
3854
3855 if (size() == 0)
3856 return *this;
3857
3858 const char16_t cc = (cs == Qt::CaseSensitive ? ch.unicode() : ch.toCaseFolded().unicode());
3859
3860 QVarLengthArray<qsizetype> indices;
3861 if (cs == Qt::CaseSensitive) {
3862 const char16_t *begin = d.begin();
3863 const char16_t *end = d.end();
3864 QStringView view(begin, end);
3865 const char16_t *hit = nullptr;
3866 while ((hit = QtPrivate::qustrchr(view, cc)) != end) {
3867 indices.push_back(std::distance(begin, hit));
3868 view = QStringView(std::next(hit), end);
3869 }
3870 } else {
3871 for (qsizetype i = 0; i < d.size; ++i)
3872 if (QChar::toCaseFolded(d.data()[i]) == cc)
3873 indices.push_back(i);
3874 }
3875 if (indices.isEmpty())
3876 return *this;
3877
3878 replace_helper(*this, indices, 1, after);
3879 return *this;
3880}
3881
3882/*!
3883 \overload replace()
3884 Replaces every occurrence of the character \a before with the
3885 character \a after and returns a reference to this string.
3886
3887 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
3888*/
3889QString& QString::replace(QChar before, QChar after, Qt::CaseSensitivity cs)
3890{
3891 const qsizetype idx = indexOf(before, 0, cs);
3892 if (idx == -1)
3893 return *this;
3894
3895 const char16_t achar = after.unicode();
3896 char16_t bchar = before.unicode();
3897
3898 auto matchesCIS = [](char16_t beforeChar) {
3899 return [beforeChar](char16_t ch) { return foldAndCompare(ch, beforeChar); };
3900 };
3901
3902 auto hit = d.begin() + idx;
3903 if (!d.needsDetach()) {
3904 *hit++ = achar;
3905 if (cs == Qt::CaseSensitive) {
3906 std::replace(hit, d.end(), bchar, achar);
3907 } else {
3908 bchar = foldCase(bchar);
3909 std::replace_if(hit, d.end(), matchesCIS(bchar), achar);
3910 }
3911 } else {
3912 QString other{ d.size, Qt::Uninitialized };
3913 auto dest = std::copy(d.begin(), hit, other.d.begin());
3914 *dest++ = achar;
3915 ++hit;
3916 if (cs == Qt::CaseSensitive) {
3917 std::replace_copy(hit, d.end(), dest, bchar, achar);
3918 } else {
3919 bchar = foldCase(bchar);
3920 std::replace_copy_if(hit, d.end(), dest, matchesCIS(bchar), achar);
3921 }
3922
3923 swap(other);
3924 }
3925 return *this;
3926}
3927
3928/*!
3929 \since 4.5
3930 \overload replace()
3931
3932 Replaces every occurrence in this string of the Latin-1 string viewed
3933 by \a before with the Latin-1 string viewed by \a after, and returns a
3934 reference to this string.
3935
3936 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
3937
3938 \note The text is not rescanned after a replacement.
3939
3940 \include qstring.cpp empty-before-arg-in-replace
3941*/
3942QString &QString::replace(QLatin1StringView before, QLatin1StringView after, Qt::CaseSensitivity cs)
3943{
3944 const qsizetype alen = after.size();
3945 const qsizetype blen = before.size();
3946 if (blen == 1 && alen == 1)
3947 return replace(before.front(), after.front(), cs);
3948
3949 QVarLengthArray<char16_t> a = qt_from_latin1_to_qvla(after);
3950 QVarLengthArray<char16_t> b = qt_from_latin1_to_qvla(before);
3951 return replace((const QChar *)b.data(), blen, (const QChar *)a.data(), alen, cs);
3952}
3953
3954/*!
3955 \since 4.5
3956 \overload replace()
3957
3958 Replaces every occurrence in this string of the Latin-1 string viewed
3959 by \a before with the string \a after, and returns a reference to this
3960 string.
3961
3962 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
3963
3964 \note The text is not rescanned after a replacement.
3965
3966 \include qstring.cpp empty-before-arg-in-replace
3967*/
3968QString &QString::replace(QLatin1StringView before, const QString &after, Qt::CaseSensitivity cs)
3969{
3970 const qsizetype blen = before.size();
3971 if (blen == 1 && after.size() == 1)
3972 return replace(before.front(), after.front(), cs);
3973
3974 QVarLengthArray<char16_t> b = qt_from_latin1_to_qvla(before);
3975 return replace((const QChar *)b.data(), blen, after.constData(), after.d.size, cs);
3976}
3977
3978/*!
3979 \since 4.5
3980 \overload replace()
3981
3982 Replaces every occurrence of the string \a before with the string \a
3983 after and returns a reference to this string.
3984
3985 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
3986
3987 \note The text is not rescanned after a replacement.
3988
3989 \include qstring.cpp empty-before-arg-in-replace
3990*/
3991QString &QString::replace(const QString &before, QLatin1StringView after, Qt::CaseSensitivity cs)
3992{
3993 const qsizetype alen = after.size();
3994 if (before.size() == 1 && alen == 1)
3995 return replace(before.front(), after.front(), cs);
3996
3997 QVarLengthArray<char16_t> a = qt_from_latin1_to_qvla(after);
3998 return replace(before.constData(), before.d.size, (const QChar *)a.data(), alen, cs);
3999}
4000
4001/*!
4002 \since 4.5
4003 \overload replace()
4004
4005 Replaces every occurrence of the character \a c with the string \a
4006 after and returns a reference to this string.
4007
4008 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
4009
4010 \note The text is not rescanned after a replacement.
4011*/
4012QString &QString::replace(QChar c, QLatin1StringView after, Qt::CaseSensitivity cs)
4013{
4014 const qsizetype alen = after.size();
4015 if (alen == 1)
4016 return replace(c, after.front(), cs);
4017
4018 QVarLengthArray<char16_t> a = qt_from_latin1_to_qvla(after);
4019 return replace(&c, 1, (const QChar *)a.data(), alen, cs);
4020}
4021
4022/*!
4023 \fn bool QString::operator==(const QString &lhs, const QString &rhs)
4024 \overload operator==()
4025
4026 Returns \c true if string \a lhs is equal to string \a rhs; otherwise
4027 returns \c false.
4028
4029 \include qstring.cpp compare-isNull-vs-isEmpty
4030
4031 \sa {Comparing Strings}
4032*/
4033
4034/*!
4035 \fn bool QString::operator==(const QString &lhs, const QLatin1StringView &rhs)
4036
4037 \overload operator==()
4038
4039 Returns \c true if \a lhs is equal to \a rhs; otherwise
4040 returns \c false.
4041*/
4042
4043/*!
4044 \fn bool QString::operator==(const QLatin1StringView &lhs, const QString &rhs)
4045
4046 \overload operator==()
4047
4048 Returns \c true if \a lhs is equal to \a rhs; otherwise
4049 returns \c false.
4050*/
4051
4052/*! \fn bool QString::operator==(const QString &lhs, const QByteArray &rhs)
4053
4054 \overload operator==()
4055
4056 The \a rhs byte array is converted to a QUtf8StringView.
4057
4058 You can disable this operator by defining
4059 \l QT_NO_CAST_FROM_ASCII when you compile your applications. This
4060 can be useful if you want to ensure that all user-visible strings
4061 go through QObject::tr(), for example.
4062
4063 Returns \c true if string \a lhs is lexically equal to \a rhs.
4064 Otherwise returns \c false.
4065*/
4066
4067/*! \fn bool QString::operator==(const QString &lhs, const char * const &rhs)
4068
4069 \overload operator==()
4070
4071 The \a rhs const char pointer is converted to a QUtf8StringView.
4072
4073 You can disable this operator by defining
4074 \l QT_NO_CAST_FROM_ASCII when you compile your applications. This
4075 can be useful if you want to ensure that all user-visible strings
4076 go through QObject::tr(), for example.
4077*/
4078
4079/*!
4080 \fn bool QString::operator<(const QString &lhs, const QString &rhs)
4081
4082 \overload operator<()
4083
4084 Returns \c true if string \a lhs is lexically less than string
4085 \a rhs; otherwise returns \c false.
4086
4087 \sa {Comparing Strings}
4088*/
4089
4090/*!
4091 \fn bool QString::operator<(const QString &lhs, const QLatin1StringView &rhs)
4092
4093 \overload operator<()
4094
4095 Returns \c true if \a lhs is lexically less than \a rhs;
4096 otherwise returns \c false.
4097*/
4098
4099/*!
4100 \fn bool QString::operator<(const QLatin1StringView &lhs, const QString &rhs)
4101
4102 \overload operator<()
4103
4104 Returns \c true if \a lhs is lexically less than \a rhs;
4105 otherwise returns \c false.
4106*/
4107
4108/*! \fn bool QString::operator<(const QString &lhs, const QByteArray &rhs)
4109
4110 \overload operator<()
4111
4112 The \a rhs byte array is converted to a QUtf8StringView.
4113 If any NUL characters ('\\0') are embedded in the byte array, they will be
4114 included in the transformation.
4115
4116 You can disable this operator
4117 \l QT_NO_CAST_FROM_ASCII when you compile your applications. This
4118 can be useful if you want to ensure that all user-visible strings
4119 go through QObject::tr(), for example.
4120*/
4121
4122/*! \fn bool QString::operator<(const QString &lhs, const char * const &rhs)
4123
4124 Returns \c true if string \a lhs is lexically less than string \a rhs.
4125 Otherwise returns \c false.
4126
4127 \overload operator<()
4128
4129 The \a rhs const char pointer is converted to a QUtf8StringView.
4130
4131 You can disable this operator by defining
4132 \l QT_NO_CAST_FROM_ASCII when you compile your applications. This
4133 can be useful if you want to ensure that all user-visible strings
4134 go through QObject::tr(), for example.
4135*/
4136
4137/*! \fn bool QString::operator<=(const QString &lhs, const QString &rhs)
4138
4139 Returns \c true if string \a lhs is lexically less than or equal to
4140 string \a rhs; otherwise returns \c false.
4141
4142 \sa {Comparing Strings}
4143*/
4144
4145/*!
4146 \fn bool QString::operator<=(const QString &lhs, const QLatin1StringView &rhs)
4147
4148 \overload operator<=()
4149
4150 Returns \c true if \a lhs is lexically less than or equal to \a rhs;
4151 otherwise returns \c false.
4152*/
4153
4154/*!
4155 \fn bool QString::operator<=(const QLatin1StringView &lhs, const QString &rhs)
4156
4157 \overload operator<=()
4158
4159 Returns \c true if \a lhs is lexically less than or equal to \a rhs;
4160 otherwise returns \c false.
4161*/
4162
4163/*! \fn bool QString::operator<=(const QString &lhs, const QByteArray &rhs)
4164
4165 \overload operator<=()
4166
4167 The \a rhs byte array is converted to a QUtf8StringView.
4168 If any NUL characters ('\\0') are embedded in the byte array, they will be
4169 included in the transformation.
4170
4171 You can disable this operator by defining
4172 \l QT_NO_CAST_FROM_ASCII when you compile your applications. This
4173 can be useful if you want to ensure that all user-visible strings
4174 go through QObject::tr(), for example.
4175*/
4176
4177/*! \fn bool QString::operator<=(const QString &lhs, const char * const &rhs)
4178
4179 \overload operator<=()
4180
4181 The \a rhs const char pointer is converted to a QUtf8StringView.
4182
4183 You can disable this operator by defining
4184 \l QT_NO_CAST_FROM_ASCII when you compile your applications. This
4185 can be useful if you want to ensure that all user-visible strings
4186 go through QObject::tr(), for example.
4187*/
4188
4189/*! \fn bool QString::operator>(const QString &lhs, const QString &rhs)
4190
4191 Returns \c true if string \a lhs is lexically greater than string \a rhs;
4192 otherwise returns \c false.
4193
4194 \sa {Comparing Strings}
4195*/
4196
4197/*!
4198 \fn bool QString::operator>(const QString &lhs, const QLatin1StringView &rhs)
4199
4200 \overload operator>()
4201
4202 Returns \c true if \a lhs is lexically greater than \a rhs;
4203 otherwise returns \c false.
4204*/
4205
4206/*!
4207 \fn bool QString::operator>(const QLatin1StringView &lhs, const QString &rhs)
4208
4209 \overload operator>()
4210
4211 Returns \c true if \a lhs is lexically greater than \a rhs;
4212 otherwise returns \c false.
4213*/
4214
4215/*! \fn bool QString::operator>(const QString &lhs, const QByteArray &rhs)
4216
4217 \overload operator>()
4218
4219 The \a rhs byte array is converted to a QUtf8StringView.
4220 If any NUL characters ('\\0') are embedded in the byte array, they will be
4221 included in the transformation.
4222
4223 You can disable this operator by defining
4224 \l QT_NO_CAST_FROM_ASCII when you compile your applications. This
4225 can be useful if you want to ensure that all user-visible strings
4226 go through QObject::tr(), for example.
4227*/
4228
4229/*! \fn bool QString::operator>(const QString &lhs, const char * const &rhs)
4230
4231 \overload operator>()
4232
4233 The \a rhs const char pointer is converted to a QUtf8StringView.
4234
4235 You can disable this operator by defining \l QT_NO_CAST_FROM_ASCII
4236 when you compile your applications. This can be useful if you want
4237 to ensure that all user-visible strings go through QObject::tr(),
4238 for example.
4239*/
4240
4241/*! \fn bool QString::operator>=(const QString &lhs, const QString &rhs)
4242
4243 Returns \c true if string \a lhs is lexically greater than or equal to
4244 string \a rhs; otherwise returns \c false.
4245
4246 \sa {Comparing Strings}
4247*/
4248
4249/*!
4250 \fn bool QString::operator>=(const QString &lhs, const QLatin1StringView &rhs)
4251
4252 \overload operator>=()
4253
4254 Returns \c true if \a lhs is lexically greater than or equal to \a rhs;
4255 otherwise returns \c false.
4256*/
4257
4258/*!
4259 \fn bool QString::operator>=(const QLatin1StringView &lhs, const QString &rhs)
4260
4261 \overload operator>=()
4262
4263 Returns \c true if \a lhs is lexically greater than or equal to \a rhs;
4264 otherwise returns \c false.
4265*/
4266
4267/*! \fn bool QString::operator>=(const QString &lhs, const QByteArray &rhs)
4268
4269 \overload operator>=()
4270
4271 The \a rhs byte array is converted to a QUtf8StringView.
4272 If any NUL characters ('\\0') are embedded in the byte array, they will be
4273 included in the transformation.
4274
4275 You can disable this operator by defining \l QT_NO_CAST_FROM_ASCII
4276 when you compile your applications. This can be useful if you want
4277 to ensure that all user-visible strings go through QObject::tr(),
4278 for example.
4279*/
4280
4281/*! \fn bool QString::operator>=(const QString &lhs, const char * const &rhs)
4282
4283 \overload operator>=()
4284
4285 The \a rhs const char pointer is converted to a QUtf8StringView.
4286
4287 You can disable this operator by defining \l QT_NO_CAST_FROM_ASCII
4288 when you compile your applications. This can be useful if you want
4289 to ensure that all user-visible strings go through QObject::tr(),
4290 for example.
4291*/
4292
4293/*! \fn bool QString::operator!=(const QString &lhs, const QString &rhs)
4294
4295 Returns \c true if string \a lhs is not equal to string \a rhs;
4296 otherwise returns \c false.
4297
4298 \sa {Comparing Strings}
4299*/
4300
4301/*! \fn bool QString::operator!=(const QString &lhs, const QLatin1StringView &rhs)
4302
4303 Returns \c true if string \a lhs is not equal to string \a rhs.
4304 Otherwise returns \c false.
4305
4306 \overload operator!=()
4307*/
4308
4309/*! \fn bool QString::operator!=(const QString &lhs, const QByteArray &rhs)
4310
4311 \overload operator!=()
4312
4313 The \a rhs byte array is converted to a QUtf8StringView.
4314 If any NUL characters ('\\0') are embedded in the byte array, they will be
4315 included in the transformation.
4316
4317 You can disable this operator by defining \l QT_NO_CAST_FROM_ASCII
4318 when you compile your applications. This can be useful if you want
4319 to ensure that all user-visible strings go through QObject::tr(),
4320 for example.
4321*/
4322
4323/*! \fn bool QString::operator!=(const QString &lhs, const char * const &rhs)
4324
4325 \overload operator!=()
4326
4327 The \a rhs const char pointer is converted to a QUtf8StringView.
4328
4329 You can disable this operator by defining
4330 \l QT_NO_CAST_FROM_ASCII when you compile your applications. This
4331 can be useful if you want to ensure that all user-visible strings
4332 go through QObject::tr(), for example.
4333*/
4334
4335/*! \fn bool QString::operator==(const QByteArray &lhs, const QString &rhs)
4336
4337 Returns \c true if byte array \a lhs is equal to the UTF-8 encoding of
4338 \a rhs; otherwise returns \c false.
4339
4340 The comparison is case sensitive.
4341
4342 You can disable this operator by defining \c
4343 QT_NO_CAST_FROM_ASCII when you compile your applications. You
4344 then need to call QString::fromUtf8(), QString::fromLatin1(),
4345 or QString::fromLocal8Bit() explicitly if you want to convert the byte
4346 array to a QString before doing the comparison.
4347*/
4348
4349/*! \fn bool QString::operator!=(const QByteArray &lhs, const QString &rhs)
4350
4351 Returns \c true if byte array \a lhs is not equal to the UTF-8 encoding of
4352 \a rhs; otherwise returns \c false.
4353
4354 The comparison is case sensitive.
4355
4356 You can disable this operator by defining \c
4357 QT_NO_CAST_FROM_ASCII when you compile your applications. You
4358 then need to call QString::fromUtf8(), QString::fromLatin1(),
4359 or QString::fromLocal8Bit() explicitly if you want to convert the byte
4360 array to a QString before doing the comparison.
4361*/
4362
4363/*! \fn bool QString::operator<(const QByteArray &lhs, const QString &rhs)
4364
4365 Returns \c true if byte array \a lhs is lexically less than the UTF-8 encoding
4366 of \a rhs; otherwise returns \c false.
4367
4368 The comparison is case sensitive.
4369
4370 You can disable this operator by defining \c
4371 QT_NO_CAST_FROM_ASCII when you compile your applications. You
4372 then need to call QString::fromUtf8(), QString::fromLatin1(),
4373 or QString::fromLocal8Bit() explicitly if you want to convert the byte
4374 array to a QString before doing the comparison.
4375*/
4376
4377/*! \fn bool QString::operator>(const QByteArray &lhs, const QString &rhs)
4378
4379 Returns \c true if byte array \a lhs is lexically greater than the UTF-8
4380 encoding of \a rhs; otherwise returns \c false.
4381
4382 The comparison is case sensitive.
4383
4384 You can disable this operator by defining \c
4385 QT_NO_CAST_FROM_ASCII when you compile your applications. You
4386 then need to call QString::fromUtf8(), QString::fromLatin1(),
4387 or QString::fromLocal8Bit() explicitly if you want to convert the byte
4388 array to a QString before doing the comparison.
4389*/
4390
4391/*! \fn bool QString::operator<=(const QByteArray &lhs, const QString &rhs)
4392
4393 Returns \c true if byte array \a lhs is lexically less than or equal to the
4394 UTF-8 encoding of \a rhs; otherwise returns \c false.
4395
4396 The comparison is case sensitive.
4397
4398 You can disable this operator by defining \c
4399 QT_NO_CAST_FROM_ASCII when you compile your applications. You
4400 then need to call QString::fromUtf8(), QString::fromLatin1(),
4401 or QString::fromLocal8Bit() explicitly if you want to convert the byte
4402 array to a QString before doing the comparison.
4403*/
4404
4405/*! \fn bool QString::operator>=(const QByteArray &lhs, const QString &rhs)
4406
4407 Returns \c true if byte array \a lhs is greater than or equal to the UTF-8
4408 encoding of \a rhs; otherwise returns \c false.
4409
4410 The comparison is case sensitive.
4411
4412 You can disable this operator by defining \c
4413 QT_NO_CAST_FROM_ASCII when you compile your applications. You
4414 then need to call QString::fromUtf8(), QString::fromLatin1(),
4415 or QString::fromLocal8Bit() explicitly if you want to convert the byte
4416 array to a QString before doing the comparison.
4417*/
4418
4419/*!
4420 \fn qsizetype QString::indexOf(const QString &str, qsizetype from, Qt::CaseSensitivity cs) const
4421 \include qstring.qdocinc {qstring-first-index-of} {string} {str}
4422
4423 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
4424
4425 Example:
4426
4427 \snippet qstring/main.cpp 24
4428
4429 \include qstring.qdocinc negative-index-start-search-from-end
4430
4431 \sa lastIndexOf(), contains(), count()
4432*/
4433
4434/*!
4435 \fn qsizetype QString::indexOf(QStringView str, qsizetype from, Qt::CaseSensitivity cs) const
4436 \since 5.14
4437 \overload indexOf()
4438
4439 \include qstring.qdocinc {qstring-first-index-of} {string view} {str}
4440
4441 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
4442
4443 \include qstring.qdocinc negative-index-start-search-from-end
4444
4445 \sa QStringView::indexOf(), lastIndexOf(), contains(), count()
4446*/
4447
4448/*!
4449 \fn qsizetype QString::indexOf(QLatin1StringView str, qsizetype from, Qt::CaseSensitivity cs) const
4450 \since 4.5
4451
4452 \include {qstring.qdocinc} {qstring-first-index-of} {Latin-1 string viewed by} {str}
4453
4454 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
4455
4456 Example:
4457
4458 \snippet qstring/main.cpp 24
4459
4460 \include qstring.qdocinc negative-index-start-search-from-end
4461
4462 \sa lastIndexOf(), contains(), count()
4463*/
4464
4465/*!
4466 \fn qsizetype QString::indexOf(QChar ch, qsizetype from, Qt::CaseSensitivity cs) const
4467 \overload indexOf()
4468
4469 \include qstring.qdocinc {qstring-first-index-of} {character} {ch}
4470*/
4471
4472/*!
4473 \fn qsizetype QString::lastIndexOf(const QString &str, qsizetype from, Qt::CaseSensitivity cs) const
4474 \include qstring.qdocinc {qstring-last-index-of} {string} {str}
4475
4476 \include qstring.qdocinc negative-index-start-search-from-end
4477
4478 Returns -1 if \a str is not found.
4479
4480 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
4481
4482 Example:
4483
4484 \snippet qstring/main.cpp 29
4485
4486 \note When searching for a 0-length \a str, the match at the end of
4487 the data is excluded from the search by a negative \a from, even
4488 though \c{-1} is normally thought of as searching from the end of the
4489 string: the match at the end is \e after the last character, so it is
4490 excluded. To include such a final empty match, either give a positive
4491 value for \a from or omit the \a from parameter entirely.
4492
4493 \sa indexOf(), contains(), count()
4494*/
4495
4496/*!
4497 \fn qsizetype QString::lastIndexOf(const QString &str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
4498 \since 6.2
4499 \overload lastIndexOf()
4500
4501 Returns the index position of the last occurrence of the string \a
4502 str in this string. Returns -1 if \a str is not found.
4503
4504 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
4505
4506 Example:
4507
4508 \snippet qstring/main.cpp 29
4509
4510 \sa indexOf(), contains(), count()
4511*/
4512
4513
4514/*!
4515 \fn qsizetype QString::lastIndexOf(QLatin1StringView str, qsizetype from, Qt::CaseSensitivity cs) const
4516 \since 4.5
4517 \overload lastIndexOf()
4518
4519 \include qstring.qdocinc {qstring-last-index-of} {Latin-1 string viewed by} {str}
4520
4521 \include qstring.qdocinc negative-index-start-search-from-end
4522
4523 Returns -1 if \a str is not found.
4524
4525 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
4526
4527 Example:
4528
4529 \snippet qstring/main.cpp 29
4530
4531 \note When searching for a 0-length \a str, the match at the end of
4532 the data is excluded from the search by a negative \a from, even
4533 though \c{-1} is normally thought of as searching from the end of the
4534 string: the match at the end is \e after the last character, so it is
4535 excluded. To include such a final empty match, either give a positive
4536 value for \a from or omit the \a from parameter entirely.
4537
4538 \sa indexOf(), contains(), count()
4539*/
4540
4541/*!
4542 \fn qsizetype QString::lastIndexOf(QLatin1StringView str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
4543 \since 6.2
4544 \overload lastIndexOf()
4545
4546 Returns the index position of the last occurrence of the string \a
4547 str in this string. Returns -1 if \a str is not found.
4548
4549 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
4550
4551 Example:
4552
4553 \snippet qstring/main.cpp 29
4554
4555 \sa indexOf(), contains(), count()
4556*/
4557
4558/*!
4559 \fn qsizetype QString::lastIndexOf(QChar ch, qsizetype from, Qt::CaseSensitivity cs) const
4560 \overload lastIndexOf()
4561
4562 \include qstring.qdocinc {qstring-last-index-of} {character} {ch}
4563*/
4564
4565/*!
4566 \fn QString::lastIndexOf(QChar ch, Qt::CaseSensitivity) const
4567 \since 6.3
4568 \overload lastIndexOf()
4569*/
4570
4571/*!
4572 \fn qsizetype QString::lastIndexOf(QStringView str, qsizetype from, Qt::CaseSensitivity cs) const
4573 \since 5.14
4574 \overload lastIndexOf()
4575
4576 \include qstring.qdocinc {qstring-last-index-of} {string view} {str}
4577
4578 \include qstring.qdocinc negative-index-start-search-from-end
4579
4580 Returns -1 if \a str is not found.
4581
4582 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
4583
4584 \note When searching for a 0-length \a str, the match at the end of
4585 the data is excluded from the search by a negative \a from, even
4586 though \c{-1} is normally thought of as searching from the end of the
4587 string: the match at the end is \e after the last character, so it is
4588 excluded. To include such a final empty match, either give a positive
4589 value for \a from or omit the \a from parameter entirely.
4590
4591 \sa indexOf(), contains(), count()
4592*/
4593
4594/*!
4595 \fn qsizetype QString::lastIndexOf(QStringView str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
4596 \since 6.2
4597 \overload lastIndexOf()
4598
4599 Returns the index position of the last occurrence of the string view \a
4600 str in this string. Returns -1 if \a str is not found.
4601
4602 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
4603
4604 \sa indexOf(), contains(), count()
4605*/
4606
4607#if QT_CONFIG(regularexpression)
4608struct QStringCapture
4609{
4610 qsizetype pos;
4611 qsizetype len;
4612 int no;
4613};
4614Q_DECLARE_TYPEINFO(QStringCapture, Q_PRIMITIVE_TYPE);
4615
4616/*!
4617 \overload replace()
4618 \since 5.0
4619
4620 Replaces every occurrence of the regular expression \a re in the
4621 string with \a after. Returns a reference to the string. For
4622 example:
4623
4624 \snippet qstring/main.cpp 87
4625
4626 For regular expressions containing capturing groups,
4627 occurrences of \b{\\1}, \b{\\2}, ..., in \a after are replaced
4628 with the string captured by the corresponding capturing group.
4629
4630 \snippet qstring/main.cpp 88
4631
4632 \sa indexOf(), lastIndexOf(), remove(), QRegularExpression, QRegularExpressionMatch
4633*/
4634QString &QString::replace(const QRegularExpression &re, const QString &after)
4635{
4636 if (!re.isValid()) {
4637 qtWarnAboutInvalidRegularExpression(re, "QString", "replace");
4638 return *this;
4639 }
4640
4641 const QString copy(*this);
4642 QRegularExpressionMatchIterator iterator = re.globalMatch(copy);
4643 if (!iterator.hasNext()) // no matches at all
4644 return *this;
4645
4646 reallocData(d.size, QArrayData::KeepSize);
4647
4648 qsizetype numCaptures = re.captureCount();
4649
4650 // 1. build the backreferences list, holding where the backreferences
4651 // are in the replacement string
4652 QVarLengthArray<QStringCapture> backReferences;
4653 const qsizetype al = after.size();
4654 const QChar *ac = after.unicode();
4655
4656 for (qsizetype i = 0; i < al - 1; i++) {
4657 if (ac[i] == u'\\') {
4658 int no = ac[i + 1].digitValue();
4659 if (no > 0 && no <= numCaptures) {
4660 QStringCapture backReference;
4661 backReference.pos = i;
4662 backReference.len = 2;
4663
4664 if (i < al - 2) {
4665 int secondDigit = ac[i + 2].digitValue();
4666 if (secondDigit != -1 && ((no * 10) + secondDigit) <= numCaptures) {
4667 no = (no * 10) + secondDigit;
4668 ++backReference.len;
4669 }
4670 }
4671
4672 backReference.no = no;
4673 backReferences.append(backReference);
4674 }
4675 }
4676 }
4677
4678 // 2. iterate on the matches. For every match, copy in chunks
4679 // - the part before the match
4680 // - the after string, with the proper replacements for the backreferences
4681
4682 qsizetype newLength = 0; // length of the new string, with all the replacements
4683 qsizetype lastEnd = 0;
4684 QVarLengthArray<QStringView> chunks;
4685 const QStringView copyView{ copy }, afterView{ after };
4686 while (iterator.hasNext()) {
4687 QRegularExpressionMatch match = iterator.next();
4688 qsizetype len;
4689 // add the part before the match
4690 len = match.capturedStart() - lastEnd;
4691 if (len > 0) {
4692 chunks << copyView.mid(lastEnd, len);
4693 newLength += len;
4694 }
4695
4696 lastEnd = 0;
4697 // add the after string, with replacements for the backreferences
4698 for (const QStringCapture &backReference : std::as_const(backReferences)) {
4699 // part of "after" before the backreference
4700 len = backReference.pos - lastEnd;
4701 if (len > 0) {
4702 chunks << afterView.mid(lastEnd, len);
4703 newLength += len;
4704 }
4705
4706 // backreference itself
4707 len = match.capturedLength(backReference.no);
4708 if (len > 0) {
4709 chunks << copyView.mid(match.capturedStart(backReference.no), len);
4710 newLength += len;
4711 }
4712
4713 lastEnd = backReference.pos + backReference.len;
4714 }
4715
4716 // add the last part of the after string
4717 len = afterView.size() - lastEnd;
4718 if (len > 0) {
4719 chunks << afterView.mid(lastEnd, len);
4720 newLength += len;
4721 }
4722
4723 lastEnd = match.capturedEnd();
4724 }
4725
4726 // 3. trailing string after the last match
4727 if (copyView.size() > lastEnd) {
4728 chunks << copyView.mid(lastEnd);
4729 newLength += copyView.size() - lastEnd;
4730 }
4731
4732 // 4. assemble the chunks together
4733 resize(newLength);
4734 qsizetype i = 0;
4735 QChar *uc = data();
4736 for (const QStringView &chunk : std::as_const(chunks)) {
4737 qsizetype len = chunk.size();
4738 memcpy(uc + i, chunk.constData(), len * sizeof(QChar));
4739 i += len;
4740 }
4741
4742 return *this;
4743}
4744#endif // QT_CONFIG(regularexpression)
4745
4746/*!
4747 Returns the number of (potentially overlapping) occurrences of
4748 the string \a str in this string.
4749
4750 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
4751
4752 \sa contains(), indexOf()
4753*/
4754
4755qsizetype QString::count(const QString &str, Qt::CaseSensitivity cs) const
4756{
4757 return QtPrivate::count(QStringView(unicode(), size()), QStringView(str.unicode(), str.size()), cs);
4758}
4759
4760/*!
4761 \overload count()
4762
4763 Returns the number of occurrences of character \a ch in the string.
4764
4765 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
4766
4767 \sa contains(), indexOf()
4768*/
4769
4770qsizetype QString::count(QChar ch, Qt::CaseSensitivity cs) const
4771{
4772 return QtPrivate::count(QStringView(unicode(), size()), ch, cs);
4773}
4774
4775/*!
4776 \since 6.0
4777 \overload count()
4778 Returns the number of (potentially overlapping) occurrences of the
4779 string view \a str in this string.
4780
4781 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
4782
4783 \sa contains(), indexOf()
4784*/
4785qsizetype QString::count(QStringView str, Qt::CaseSensitivity cs) const
4786{
4787 return QtPrivate::count(*this, str, cs);
4788}
4789
4790/*! \fn bool QString::contains(const QString &str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
4791
4792 Returns \c true if this string contains an occurrence of the string
4793 \a str; otherwise returns \c false.
4794
4795 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
4796
4797 Example:
4798 \snippet qstring/main.cpp 17
4799
4800 \sa indexOf(), count()
4801*/
4802
4803/*! \fn bool QString::contains(QLatin1StringView str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
4804 \since 5.3
4805
4806 \overload contains()
4807
4808 Returns \c true if this string contains an occurrence of the latin-1 string
4809 \a str; otherwise returns \c false.
4810*/
4811
4812/*! \fn bool QString::contains(QChar ch, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
4813
4814 \overload contains()
4815
4816 Returns \c true if this string contains an occurrence of the
4817 character \a ch; otherwise returns \c false.
4818*/
4819
4820/*! \fn bool QString::contains(QStringView str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
4821 \since 5.14
4822 \overload contains()
4823
4824 Returns \c true if this string contains an occurrence of the string view
4825 \a str; otherwise returns \c false.
4826
4827 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
4828
4829 \sa indexOf(), count()
4830*/
4831
4832#if QT_CONFIG(regularexpression)
4833/*!
4834 \since 5.5
4835
4836 Returns the index position of the first match of the regular
4837 expression \a re in the string, searching forward from index
4838 position \a from. Returns -1 if \a re didn't match anywhere.
4839
4840 If the match is successful and \a rmatch is not \nullptr, it also
4841 writes the results of the match into the QRegularExpressionMatch object
4842 pointed to by \a rmatch.
4843
4844 Example:
4845
4846 \snippet qstring/main.cpp 93
4847*/
4848qsizetype QString::indexOf(const QRegularExpression &re, qsizetype from, QRegularExpressionMatch *rmatch) const
4849{
4850 return QtPrivate::indexOf(QStringView(*this), this, re, from, rmatch);
4851}
4852
4853/*!
4854 \since 5.5
4855
4856 Returns the index position of the last match of the regular
4857 expression \a re in the string, which starts before the index
4858 position \a from.
4859
4860 \include qstring.qdocinc negative-index-start-search-from-end
4861
4862 Returns -1 if \a re didn't match anywhere.
4863
4864 If the match is successful and \a rmatch is not \nullptr, it also
4865 writes the results of the match into the QRegularExpressionMatch object
4866 pointed to by \a rmatch.
4867
4868 Example:
4869
4870 \snippet qstring/main.cpp 94
4871
4872 \note Due to how the regular expression matching algorithm works,
4873 this function will actually match repeatedly from the beginning of
4874 the string until the position \a from is reached.
4875
4876 \note When searching for a regular expression \a re that may match
4877 0 characters, the match at the end of the data is excluded from the
4878 search by a negative \a from, even though \c{-1} is normally
4879 thought of as searching from the end of the string: the match at
4880 the end is \e after the last character, so it is excluded. To
4881 include such a final empty match, either give a positive value for
4882 \a from or omit the \a from parameter entirely.
4883*/
4884qsizetype QString::lastIndexOf(const QRegularExpression &re, qsizetype from, QRegularExpressionMatch *rmatch) const
4885{
4886 return QtPrivate::lastIndexOf(QStringView(*this), this, re, from, rmatch);
4887}
4888
4889/*!
4890 \fn qsizetype QString::lastIndexOf(const QRegularExpression &re, QRegularExpressionMatch *rmatch = nullptr) const
4891 \since 6.2
4892 \overload lastIndexOf()
4893
4894 Returns the index position of the last match of the regular
4895 expression \a re in the string. Returns -1 if \a re didn't match anywhere.
4896
4897 If the match is successful and \a rmatch is not \nullptr, it also
4898 writes the results of the match into the QRegularExpressionMatch object
4899 pointed to by \a rmatch.
4900
4901 Example:
4902
4903 \snippet qstring/main.cpp 94
4904
4905 \note Due to how the regular expression matching algorithm works,
4906 this function will actually match repeatedly from the beginning of
4907 the string until the end of the string is reached.
4908*/
4909
4910/*!
4911 \since 5.1
4912
4913 Returns \c true if the regular expression \a re matches somewhere in this
4914 string; otherwise returns \c false.
4915
4916 If the match is successful and \a rmatch is not \nullptr, it also
4917 writes the results of the match into the QRegularExpressionMatch object
4918 pointed to by \a rmatch.
4919
4920 \sa QRegularExpression::match()
4921*/
4922
4923bool QString::contains(const QRegularExpression &re, QRegularExpressionMatch *rmatch) const
4924{
4925 return QtPrivate::contains(QStringView(*this), this, re, rmatch);
4926}
4927
4928/*!
4929 \overload count()
4930 \since 5.0
4931
4932 Returns the number of times the regular expression \a re matches
4933 in the string.
4934
4935 For historical reasons, this function counts overlapping matches,
4936 so in the example below, there are four instances of "ana" or
4937 "ama":
4938
4939 \snippet qstring/main.cpp 95
4940
4941 This behavior is different from simply iterating over the matches
4942 in the string using QRegularExpressionMatchIterator.
4943
4944 \sa QRegularExpression::globalMatch()
4945*/
4946qsizetype QString::count(const QRegularExpression &re) const
4947{
4948 return QtPrivate::count(QStringView(*this), re);
4949}
4950#endif // QT_CONFIG(regularexpression)
4951
4952#if QT_DEPRECATED_SINCE(6, 4)
4953/*! \fn qsizetype QString::count() const
4954 \deprecated [6.4] Use size() or length() instead.
4955 \overload count()
4956
4957 Same as size().
4958*/
4959#endif
4960
4961/*!
4962 \enum QString::SectionFlag
4963
4964 This enum specifies flags that can be used to affect various
4965 aspects of the section() function's behavior with respect to
4966 separators and empty fields.
4967
4968 \value SectionDefault Empty fields are counted, leading and
4969 trailing separators are not included, and the separator is
4970 compared case sensitively.
4971
4972 \value SectionSkipEmpty Treat empty fields as if they don't exist,
4973 i.e. they are not considered as far as \e start and \e end are
4974 concerned.
4975
4976 \value SectionIncludeLeadingSep Include the leading separator (if
4977 any) in the result string.
4978
4979 \value SectionIncludeTrailingSep Include the trailing separator
4980 (if any) in the result string.
4981
4982 \value SectionCaseInsensitiveSeps Compare the separator
4983 case-insensitively.
4984
4985 \sa section()
4986*/
4987
4988/*!
4989 \fn QString QString::section(QChar sep, qsizetype start, qsizetype end = -1, SectionFlags flags) const
4990
4991 This function returns a section of the string.
4992
4993 This string is treated as a sequence of fields separated by the
4994 character, \a sep. The returned string consists of the fields from
4995 position \a start to position \a end inclusive. If \a end is not
4996 specified, all fields from position \a start to the end of the
4997 string are included. Fields are numbered 0, 1, 2, etc., counting
4998 from the left, and -1, -2, etc., counting from right to left.
4999
5000 The \a flags argument can be used to affect some aspects of the
5001 function's behavior, e.g. whether to be case sensitive, whether
5002 to skip empty fields and how to deal with leading and trailing
5003 separators; see \l{SectionFlags}.
5004
5005 \snippet qstring/main.cpp 52
5006
5007 If \a start or \a end is negative, we count fields from the right
5008 of the string, the right-most field being -1, the one from
5009 right-most field being -2, and so on.
5010
5011 \snippet qstring/main.cpp 53
5012
5013 \sa split()
5014*/
5015
5016/*!
5017 \overload section()
5018
5019 \snippet qstring/main.cpp 51
5020 \snippet qstring/main.cpp 54
5021
5022 \sa split()
5023*/
5024
5025QString QString::section(const QString &sep, qsizetype start, qsizetype end, SectionFlags flags) const
5026{
5027 const QList<QStringView> sections = QStringView{ *this }.split(
5028 sep, Qt::KeepEmptyParts, (flags & SectionCaseInsensitiveSeps) ? Qt::CaseInsensitive : Qt::CaseSensitive);
5029 const qsizetype sectionsSize = sections.size();
5030 if (!(flags & SectionSkipEmpty)) {
5031 if (start < 0)
5032 start += sectionsSize;
5033 if (end < 0)
5034 end += sectionsSize;
5035 } else {
5036 qsizetype skip = 0;
5037 for (qsizetype k = 0; k < sectionsSize; ++k) {
5038 if (sections.at(k).isEmpty())
5039 skip++;
5040 }
5041 if (start < 0)
5042 start += sectionsSize - skip;
5043 if (end < 0)
5044 end += sectionsSize - skip;
5045 }
5046 if (start >= sectionsSize || end < 0 || start > end)
5047 return QString();
5048
5049 QString ret;
5050 qsizetype first_i = start, last_i = end;
5051 for (qsizetype x = 0, i = 0; x <= end && i < sectionsSize; ++i) {
5052 const QStringView &section = sections.at(i);
5053 const bool empty = section.isEmpty();
5054 if (x >= start) {
5055 if (x == start)
5056 first_i = i;
5057 if (x == end)
5058 last_i = i;
5059 if (x > start && i > 0)
5060 ret += sep;
5061 ret += section;
5062 }
5063 if (!empty || !(flags & SectionSkipEmpty))
5064 x++;
5065 }
5066 if ((flags & SectionIncludeLeadingSep) && first_i > 0)
5067 ret.prepend(sep);
5068 if ((flags & SectionIncludeTrailingSep) && last_i < sectionsSize - 1)
5069 ret += sep;
5070 return ret;
5071}
5072
5073#if QT_CONFIG(regularexpression)
5074struct qt_section_chunk
5075{
5076 qsizetype length;
5077 QStringView string;
5078};
5079Q_DECLARE_TYPEINFO(qt_section_chunk, Q_RELOCATABLE_TYPE);
5080
5081static QString extractSections(QSpan<qt_section_chunk> sections, qsizetype start, qsizetype end,
5082 QString::SectionFlags flags)
5083{
5084 const qsizetype sectionsSize = sections.size();
5085
5086 if (!(flags & QString::SectionSkipEmpty)) {
5087 if (start < 0)
5088 start += sectionsSize;
5089 if (end < 0)
5090 end += sectionsSize;
5091 } else {
5092 qsizetype skip = 0;
5093 for (qsizetype k = 0; k < sectionsSize; ++k) {
5094 const qt_section_chunk &section = sections[k];
5095 if (section.length == section.string.size())
5096 skip++;
5097 }
5098 if (start < 0)
5099 start += sectionsSize - skip;
5100 if (end < 0)
5101 end += sectionsSize - skip;
5102 }
5103 if (start >= sectionsSize || end < 0 || start > end)
5104 return QString();
5105
5106 QString ret;
5107 qsizetype x = 0;
5108 qsizetype first_i = start, last_i = end;
5109 for (qsizetype i = 0; x <= end && i < sectionsSize; ++i) {
5110 const qt_section_chunk &section = sections[i];
5111 const bool empty = (section.length == section.string.size());
5112 if (x >= start) {
5113 if (x == start)
5114 first_i = i;
5115 if (x == end)
5116 last_i = i;
5117 if (x != start)
5118 ret += section.string;
5119 else
5120 ret += section.string.mid(section.length);
5121 }
5122 if (!empty || !(flags & QString::SectionSkipEmpty))
5123 x++;
5124 }
5125
5126 if ((flags & QString::SectionIncludeLeadingSep) && first_i >= 0) {
5127 const qt_section_chunk &section = sections[first_i];
5128 ret.prepend(section.string.left(section.length));
5129 }
5130
5131 if ((flags & QString::SectionIncludeTrailingSep)
5132 && last_i < sectionsSize - 1) {
5133 const qt_section_chunk &section = sections[last_i + 1];
5134 ret += section.string.left(section.length);
5135 }
5136
5137 return ret;
5138}
5139
5140/*!
5141 \overload section()
5142 \since 5.0
5143
5144 This string is treated as a sequence of fields separated by the
5145 regular expression, \a re.
5146
5147 \snippet qstring/main.cpp 89
5148
5149 \warning Using this QRegularExpression version is much more expensive than
5150 the overloaded string and character versions.
5151
5152 \sa split(), simplified()
5153*/
5154QString QString::section(const QRegularExpression &re, qsizetype start, qsizetype end, SectionFlags flags) const
5155{
5156 if (!re.isValid()) {
5157 qtWarnAboutInvalidRegularExpression(re, "QString", "section");
5158 return QString();
5159 }
5160
5161 const QChar *uc = unicode();
5162 if (!uc)
5163 return QString();
5164
5165 QRegularExpression sep(re);
5166 if (flags & SectionCaseInsensitiveSeps)
5167 sep.setPatternOptions(sep.patternOptions() | QRegularExpression::CaseInsensitiveOption);
5168
5169 QVarLengthArray<qt_section_chunk> sections;
5170 qsizetype n = size(), m = 0, last_m = 0, last_len = 0;
5171 QRegularExpressionMatchIterator iterator = sep.globalMatch(*this);
5172 while (iterator.hasNext()) {
5173 QRegularExpressionMatch match = iterator.next();
5174 m = match.capturedStart();
5175 sections.append(qt_section_chunk{last_len, QStringView{*this}.sliced(last_m, m - last_m)});
5176 last_m = m;
5177 last_len = match.capturedLength();
5178 }
5179 sections.append(qt_section_chunk{last_len, QStringView{*this}.sliced(last_m, n - last_m)});
5180
5181 return extractSections(sections, start, end, flags);
5182}
5183#endif // QT_CONFIG(regularexpression)
5184
5185/*!
5186 \fn QString QString::left(qsizetype n) const &
5187 \fn QString QString::left(qsizetype n) &&
5188
5189 Returns a substring that contains the \a n leftmost characters of
5190 this string (that is, from the beginning of this string up to, but not
5191 including, the element at index position \a n).
5192
5193 If you know that \a n cannot be out of bounds, use first() instead in new
5194 code, because it is faster.
5195
5196 The entire string is returned if \a n is greater than or equal
5197 to size(), or less than zero.
5198
5199 \sa first(), last(), startsWith(), chopped(), chop(), truncate()
5200*/
5201
5202/*!
5203 \fn QString QString::right(qsizetype n) const &
5204 \fn QString QString::right(qsizetype n) &&
5205
5206 Returns a substring that contains the \a n rightmost characters
5207 of the string.
5208
5209 If you know that \a n cannot be out of bounds, use last() instead in new
5210 code, because it is faster.
5211
5212 The entire string is returned if \a n is greater than or equal
5213 to size(), or less than zero.
5214
5215 \sa endsWith(), last(), first(), sliced(), chopped(), chop(), truncate(), slice()
5216*/
5217
5218/*!
5219 \fn QString QString::mid(qsizetype position, qsizetype n) const &
5220 \fn QString QString::mid(qsizetype position, qsizetype n) &&
5221
5222 Returns a string that contains \a n characters of this string, starting
5223 at the specified \a position index up to, but not including, the element
5224 at index position \tt {\a position + \a n}.
5225
5226 If you know that \a position and \a n cannot be out of bounds, use sliced()
5227 instead in new code, because it is faster.
5228
5229 Returns a null string if the \a position index exceeds the
5230 length of the string. If there are less than \a n characters
5231 available in the string starting at the given \a position, or if
5232 \a n is -1 (default), the function returns all characters that
5233 are available from the specified \a position.
5234
5235 \sa first(), last(), sliced(), chopped(), chop(), truncate(), slice()
5236*/
5237QString QString::mid(qsizetype position, qsizetype n) const &
5238{
5239 qsizetype p = position;
5240 qsizetype l = n;
5241 using namespace QtPrivate;
5242 switch (QContainerImplHelper::mid(size(), &p, &l)) {
5243 case QContainerImplHelper::Null:
5244 return QString();
5245 case QContainerImplHelper::Empty:
5246 return QString(DataPointer::fromRawData(&_empty, 0));
5247 case QContainerImplHelper::Full:
5248 return *this;
5249 case QContainerImplHelper::Subset:
5250 return sliced(p, l);
5251 }
5252 Q_UNREACHABLE_RETURN(QString());
5253}
5254
5255QString QString::mid(qsizetype position, qsizetype n) &&
5256{
5257 qsizetype p = position;
5258 qsizetype l = n;
5259 using namespace QtPrivate;
5260 switch (QContainerImplHelper::mid(size(), &p, &l)) {
5261 case QContainerImplHelper::Null:
5262 return QString();
5263 case QContainerImplHelper::Empty:
5264 resize(0); // keep capacity if we've reserve()d
5265 [[fallthrough]];
5266 case QContainerImplHelper::Full:
5267 return std::move(*this);
5268 case QContainerImplHelper::Subset:
5269 return std::move(*this).sliced(p, l);
5270 }
5271 Q_UNREACHABLE_RETURN(QString());
5272}
5273
5274/*!
5275 \fn QString QString::first(qsizetype n) const &
5276 \fn QString QString::first(qsizetype n) &&
5277 \since 6.0
5278
5279 Returns a string that contains the first \a n characters of this string,
5280 (that is, from the beginning of this string up to, but not including,
5281 the element at index position \a n).
5282
5283 \note The behavior is undefined when \a n < 0 or \a n > size().
5284
5285 \snippet qstring/main.cpp 31
5286
5287 \sa last(), sliced(), startsWith(), chopped(), chop(), truncate(), slice()
5288*/
5289
5290/*!
5291 \fn QString QString::last(qsizetype n) const &
5292 \fn QString QString::last(qsizetype n) &&
5293 \since 6.0
5294
5295 Returns the string that contains the last \a n characters of this string.
5296
5297 \note The behavior is undefined when \a n < 0 or \a n > size().
5298
5299 \snippet qstring/main.cpp 48
5300
5301 \sa first(), sliced(), endsWith(), chopped(), chop(), truncate(), slice()
5302*/
5303
5304/*!
5305 \fn QString QString::sliced(qsizetype pos, qsizetype n) const &
5306 \fn QString QString::sliced(qsizetype pos, qsizetype n) &&
5307 \since 6.0
5308
5309 Returns a string that contains \a n characters of this string, starting
5310 at position \a pos up to, but not including, the element at index position
5311 \tt {\a pos + \a n}.
5312
5313 \note The behavior is undefined when \a pos < 0, \a n < 0,
5314 or \a pos + \a n > size().
5315
5316 \snippet qstring/main.cpp 34
5317
5318 \sa first(), last(), chopped(), chop(), truncate(), slice()
5319*/
5320QString QString::sliced_helper(QString &str, qsizetype pos, qsizetype n)
5321{
5322 if (n == 0)
5323 return QString(DataPointer::fromRawData(&_empty, 0));
5324 DataPointer d = std::move(str.d).sliced(pos, n);
5325 d.data()[n] = 0;
5326 return QString(std::move(d));
5327}
5328
5329/*!
5330 \fn QString QString::sliced(qsizetype pos) const &
5331 \fn QString QString::sliced(qsizetype pos) &&
5332 \since 6.0
5333 \overload
5334
5335 Returns a string that contains the portion of this string starting at
5336 position \a pos and extending to its end.
5337
5338 \note The behavior is undefined when \a pos < 0 or \a pos > size().
5339
5340 \sa first(), last(), chopped(), chop(), truncate(), slice()
5341*/
5342
5343/*!
5344 \fn QString &QString::slice(qsizetype pos, qsizetype n)
5345 \since 6.8
5346
5347 Modifies this string to start at position \a pos, up to, but not including,
5348 the character (code point) at index position \tt {\a pos + \a n}; and
5349 returns a reference to this string.
5350
5351 \note The behavior is undefined if \a pos < 0, \a n < 0,
5352 or \a pos + \a n > size().
5353
5354 \snippet qstring/main.cpp slice97
5355
5356 \sa sliced(), first(), last(), chopped(), chop(), truncate()
5357*/
5358
5359/*!
5360 \fn QString &QString::slice(qsizetype pos)
5361 \since 6.8
5362 \overload
5363
5364 Modifies this string to start at position \a pos and extending to its end,
5365 and returns a reference to this string.
5366
5367 \note The behavior is undefined if \a pos < 0 or \a pos > size().
5368
5369 \sa sliced(), first(), last(), chopped(), chop(), truncate()
5370*/
5371
5372/*!
5373 \fn QString QString::chopped(qsizetype len) const &
5374 \fn QString QString::chopped(qsizetype len) &&
5375 \since 5.10
5376
5377 Returns a string that contains the size() - \a len leftmost characters
5378 of this string.
5379
5380 \note The behavior is undefined if \a len is negative or greater than size().
5381
5382 \sa endsWith(), first(), last(), sliced(), chop(), truncate(), slice()
5383*/
5384
5385/*!
5386 Returns \c true if the string starts with \a s; otherwise returns
5387 \c false.
5388
5389 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
5390
5391 \snippet qstring/main.cpp 65
5392
5393 \sa endsWith()
5394*/
5395bool QString::startsWith(const QString& s, Qt::CaseSensitivity cs) const
5396{
5397 return qt_starts_with_impl(QStringView(*this), QStringView(s), cs);
5398}
5399
5400/*!
5401 \overload startsWith()
5402 */
5403bool QString::startsWith(QLatin1StringView s, Qt::CaseSensitivity cs) const
5404{
5405 return qt_starts_with_impl(QStringView(*this), s, cs);
5406}
5407
5408/*!
5409 \overload startsWith()
5410
5411 Returns \c true if the string starts with \a c; otherwise returns
5412 \c false.
5413*/
5414bool QString::startsWith(QChar c, Qt::CaseSensitivity cs) const
5415{
5416 if (!size())
5417 return false;
5418 if (cs == Qt::CaseSensitive)
5419 return at(0) == c;
5420 return foldCase(at(0)) == foldCase(c);
5421}
5422
5423/*!
5424 \fn bool QString::startsWith(QStringView str, Qt::CaseSensitivity cs) const
5425 \since 5.10
5426 \overload
5427
5428 Returns \c true if the string starts with the string view \a str;
5429 otherwise returns \c false.
5430
5431 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
5432
5433 \sa endsWith()
5434*/
5435
5436/*!
5437 Returns \c true if the string ends with \a s; otherwise returns
5438 \c false.
5439
5440 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
5441
5442 \snippet qstring/main.cpp 20
5443
5444 \sa startsWith()
5445*/
5446bool QString::endsWith(const QString &s, Qt::CaseSensitivity cs) const
5447{
5448 return qt_ends_with_impl(QStringView(*this), QStringView(s), cs);
5449}
5450
5451/*!
5452 \fn bool QString::endsWith(QStringView str, Qt::CaseSensitivity cs) const
5453 \since 5.10
5454 \overload endsWith()
5455 Returns \c true if the string ends with the string view \a str;
5456 otherwise returns \c false.
5457
5458 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
5459
5460 \sa startsWith()
5461*/
5462
5463/*!
5464 \overload endsWith()
5465*/
5466bool QString::endsWith(QLatin1StringView s, Qt::CaseSensitivity cs) const
5467{
5468 return qt_ends_with_impl(QStringView(*this), s, cs);
5469}
5470
5471/*!
5472 Returns \c true if the string ends with \a c; otherwise returns
5473 \c false.
5474
5475 \overload endsWith()
5476 */
5477bool QString::endsWith(QChar c, Qt::CaseSensitivity cs) const
5478{
5479 if (!size())
5480 return false;
5481 if (cs == Qt::CaseSensitive)
5482 return at(size() - 1) == c;
5483 return foldCase(at(size() - 1)) == foldCase(c);
5484}
5485
5486static bool checkCase(QStringView s, QUnicodeTables::Case c) noexcept
5487{
5488 QStringIterator it(s);
5489 while (it.hasNext()) {
5490 const char32_t uc = it.next();
5491 if (caseConversion(uc)[c].diff)
5492 return false;
5493 }
5494 return true;
5495}
5496
5497bool QtPrivate::isLower(QStringView s) noexcept
5498{
5499 return checkCase(s, QUnicodeTables::LowerCase);
5500}
5501
5502bool QtPrivate::isUpper(QStringView s) noexcept
5503{
5504 return checkCase(s, QUnicodeTables::UpperCase);
5505}
5506
5507/*!
5508 Returns \c true if the string is uppercase, that is, it's identical
5509 to its toUpper() folding.
5510
5511 Note that this does \e not mean that the string does not contain
5512 lowercase letters (some lowercase letters do not have a uppercase
5513 folding; they are left unchanged by toUpper()).
5514 For more information, refer to the Unicode standard, section 3.13.
5515
5516 \since 5.12
5517
5518 \sa QChar::toUpper(), isLower()
5519*/
5520bool QString::isUpper() const
5521{
5522 return QtPrivate::isUpper(qToStringViewIgnoringNull(*this));
5523}
5524
5525/*!
5526 Returns \c true if the string is lowercase, that is, it's identical
5527 to its toLower() folding.
5528
5529 Note that this does \e not mean that the string does not contain
5530 uppercase letters (some uppercase letters do not have a lowercase
5531 folding; they are left unchanged by toLower()).
5532 For more information, refer to the Unicode standard, section 3.13.
5533
5534 \since 5.12
5535
5536 \sa QChar::toLower(), isUpper()
5537 */
5538bool QString::isLower() const
5539{
5540 return QtPrivate::isLower(qToStringViewIgnoringNull(*this));
5541}
5542
5543static QByteArray qt_convert_to_latin1(QStringView string);
5544
5545QByteArray QString::toLatin1_helper(const QString &string)
5546{
5547 return qt_convert_to_latin1(string);
5548}
5549
5550/*!
5551 \since 6.0
5552 \internal
5553 \relates QAnyStringView
5554
5555 Returns a UTF-16 representation of \a string as a QString.
5556
5557 \sa QString::toLatin1(), QStringView::toLatin1(), QtPrivate::convertToUtf8(),
5558 QtPrivate::convertToLocal8Bit(), QtPrivate::convertToUcs4()
5559*/
5560QString QtPrivate::convertToQString(QAnyStringView string)
5561{
5562 return string.visit([] (auto string) { return string.toString(); });
5563}
5564
5565/*!
5566 \since 5.10
5567 \internal
5568 \relates QStringView
5569
5570 Returns a Latin-1 representation of \a string as a QByteArray.
5571
5572 The behavior is undefined if \a string contains non-Latin1 characters.
5573
5574 \sa QString::toLatin1(), QStringView::toLatin1(), QtPrivate::convertToUtf8(),
5575 QtPrivate::convertToLocal8Bit(), QtPrivate::convertToUcs4()
5576*/
5578{
5579 return qt_convert_to_latin1(string);
5580}
5581
5582Q_NEVER_INLINE
5583static QByteArray qt_convert_to_latin1(QStringView string)
5584{
5585 if (Q_UNLIKELY(string.isNull()))
5586 return QByteArray();
5587
5588 QByteArray ba(string.size(), Qt::Uninitialized);
5589
5590 // since we own the only copy, we're going to const_cast the constData;
5591 // that avoids an unnecessary call to detach() and expansion code that will never get used
5592 qt_to_latin1(reinterpret_cast<uchar *>(const_cast<char *>(ba.constData())),
5593 string.utf16(), string.size());
5594 return ba;
5595}
5596
5597QByteArray QString::toLatin1_helper_inplace(QString &s)
5598{
5599 if (!s.isDetached())
5600 return qt_convert_to_latin1(s);
5601
5602 // We can return our own buffer to the caller.
5603 // Conversion to Latin-1 always shrinks the buffer by half.
5604 // This relies on the fact that we use QArrayData for everything behind the scenes
5605
5606 // First, do the in-place conversion. Since isDetached() == true, the data
5607 // was allocated by QArrayData, so the null terminator must be there.
5608 qsizetype length = s.size();
5609 char16_t *sdata = s.d.data();
5610 Q_ASSERT(sdata[length] == u'\0');
5611 qt_to_latin1(reinterpret_cast<uchar *>(sdata), sdata, length + 1);
5612
5613 // Move the internals over to the byte array.
5614 // Kids, avert your eyes. Don't try this at home.
5615 auto ba_d = std::move(s.d).reinterpreted<char>();
5616
5617 // Some sanity checks
5618 Q_ASSERT(ba_d.d->allocatedCapacity() >= ba_d.size);
5619 Q_ASSERT(s.isNull());
5620 Q_ASSERT(s.isEmpty());
5621 Q_ASSERT(s.constData() == QString().constData());
5622
5623 return QByteArray(std::move(ba_d));
5624}
5625
5626/*!
5627 \since 6.9
5628 \internal
5629 \relates QLatin1StringView
5630
5631 Returns a UTF-8 representation of \a string as a QByteArray.
5632*/
5633QByteArray QtPrivate::convertToUtf8(QLatin1StringView string)
5634{
5635 if (Q_UNLIKELY(string.isNull()))
5636 return QByteArray();
5637
5638 // create a QByteArray with the worst case scenario size
5639 QByteArray ba(string.size() * 2, Qt::Uninitialized);
5640 const qsizetype sz = QUtf8::convertFromLatin1(ba.data(), string) - ba.data();
5641 ba.truncate(sz);
5642
5643 return ba;
5644}
5645
5646// QLatin1 methods that use helpers from qstring.cpp
5647char16_t *QLatin1::convertToUnicode(char16_t *out, QLatin1StringView in) noexcept
5648{
5649 const qsizetype len = in.size();
5650 qt_from_latin1(out, in.data(), len);
5651 return std::next(out, len);
5652}
5653
5654char *QLatin1::convertFromUnicode(char *out, QStringView in) noexcept
5655{
5656 const qsizetype len = in.size();
5657 qt_to_latin1(reinterpret_cast<uchar *>(out), in.utf16(), len);
5658 return out + len;
5659}
5660
5661/*!
5662 \fn QByteArray QString::toLatin1() const
5663
5664 Returns a Latin-1 representation of the string as a QByteArray.
5665
5666 The returned byte array is undefined if the string contains non-Latin1
5667 characters. Those characters may be suppressed or replaced with a
5668 question mark.
5669
5670 \sa fromLatin1(), toUtf8(), toLocal8Bit(), QStringEncoder
5671*/
5672
5673static QByteArray qt_convert_to_local_8bit(QStringView string);
5674
5675/*!
5676 \fn QByteArray QString::toLocal8Bit() const
5677
5678 Returns the local 8-bit representation of the string as a
5679 QByteArray.
5680
5681 \include qstring.qdocinc {qstring-local-8-bit-equivalent} {toUtf8}
5682
5683 If this string contains any characters that cannot be encoded in the
5684 local 8-bit encoding, the returned byte array is undefined. Those
5685 characters may be suppressed or replaced by another.
5686
5687 \sa fromLocal8Bit(), toLatin1(), toUtf8(), QStringEncoder
5688*/
5689
5690QByteArray QString::toLocal8Bit_helper(const QChar *data, qsizetype size)
5691{
5692 return qt_convert_to_local_8bit(QStringView(data, size));
5693}
5694
5695static QByteArray qt_convert_to_local_8bit(QStringView string)
5696{
5697 if (string.isNull())
5698 return QByteArray();
5699 QStringEncoder fromUtf16(QStringEncoder::System, QStringEncoder::Flag::Stateless);
5700 return fromUtf16(string);
5701}
5702
5703/*!
5704 \since 5.10
5705 \internal
5706 \relates QStringView
5707
5708 Returns a local 8-bit representation of \a string as a QByteArray.
5709
5710 On Unix systems this is equivalent to toUtf8(), on Windows the systems
5711 current code page is being used.
5712
5713 The behavior is undefined if \a string contains characters not
5714 supported by the locale's 8-bit encoding.
5715
5716 \sa QString::toLocal8Bit(), QStringView::toLocal8Bit()
5717*/
5719{
5720 return qt_convert_to_local_8bit(string);
5721}
5722
5723static QByteArray qt_convert_to_utf8(QStringView str);
5724
5725/*!
5726 \fn QByteArray QString::toUtf8() const
5727
5728 Returns a UTF-8 representation of the string as a QByteArray.
5729
5730 UTF-8 is a Unicode codec and can represent all characters in a Unicode
5731 string like QString.
5732
5733 \sa fromUtf8(), toLatin1(), toLocal8Bit(), QStringEncoder
5734*/
5735
5736QByteArray QString::toUtf8_helper(const QString &str)
5737{
5738 return qt_convert_to_utf8(str);
5739}
5740
5741static QByteArray qt_convert_to_utf8(QStringView str)
5742{
5743 if (str.isNull())
5744 return QByteArray();
5745
5746 return QUtf8::convertFromUnicode(str);
5747}
5748
5749/*!
5750 \since 5.10
5751 \internal
5752 \relates QStringView
5753
5754 Returns a UTF-8 representation of \a string as a QByteArray.
5755
5756 UTF-8 is a Unicode codec and can represent all characters in a Unicode
5757 string like QStringView.
5758
5759 \sa QString::toUtf8(), QStringView::toUtf8()
5760*/
5762{
5763 return qt_convert_to_utf8(string);
5764}
5765
5766static QList<uint> qt_convert_to_ucs4(QStringView string);
5767
5768/*!
5769 \since 4.2
5770
5771 Returns a UCS-4/UTF-32 representation of the string as a QList<uint>.
5772
5773 UTF-32 is a Unicode codec and therefore it is lossless. All characters from
5774 this string will be encoded in UTF-32. Any invalid sequence of code units in
5775 this string is replaced by the Unicode replacement character
5776 (QChar::ReplacementCharacter, which corresponds to \c{U+FFFD}).
5777
5778 The returned list is not 0-terminated.
5779
5780 \sa fromUtf8(), toUtf8(), toLatin1(), toLocal8Bit(), QStringEncoder,
5781 fromUcs4(), toWCharArray()
5782*/
5783QList<uint> QString::toUcs4() const
5784{
5785 return qt_convert_to_ucs4(*this);
5786}
5787
5788static QList<uint> qt_convert_to_ucs4(QStringView string)
5789{
5790 QList<uint> v(string.size());
5791 uint *a = const_cast<uint*>(v.constData());
5792 QStringIterator it(string);
5793 while (it.hasNext())
5794 *a++ = it.next();
5795 v.resize(a - v.constData());
5796 return v;
5797}
5798
5799/*!
5800 \since 5.10
5801 \internal
5802 \relates QStringView
5803
5804 Returns a UCS-4/UTF-32 representation of \a string as a QList<uint>.
5805
5806 UTF-32 is a Unicode codec and therefore it is lossless. All characters from
5807 this string will be encoded in UTF-32. Any invalid sequence of code units in
5808 this string is replaced by the Unicode replacement character
5809 (QChar::ReplacementCharacter, which corresponds to \c{U+FFFD}).
5810
5811 The returned list is not 0-terminated.
5812
5813 \sa QString::toUcs4(), QStringView::toUcs4(), QtPrivate::convertToLatin1(),
5814 QtPrivate::convertToLocal8Bit(), QtPrivate::convertToUtf8()
5815*/
5816QList<uint> QtPrivate::convertToUcs4(QStringView string)
5817{
5818 return qt_convert_to_ucs4(string);
5819}
5820
5821/*!
5822 \fn QString QString::fromLatin1(QByteArrayView str)
5823 \overload
5824 \since 6.0
5825
5826 Returns a QString initialized with the Latin-1 string \a str.
5827
5828 \note: any null ('\\0') bytes in the byte array will be included in this
5829 string, converted to Unicode null characters (U+0000).
5830*/
5831QString QString::fromLatin1(QByteArrayView ba)
5832{
5833 DataPointer d;
5834 if (!ba.data()) {
5835 // nothing to do
5836 } else if (ba.size() == 0) {
5837 d = DataPointer::fromRawData(&_empty, 0);
5838 } else {
5839 d = DataPointer(ba.size(), ba.size());
5840 Q_CHECK_PTR(d.data());
5841 d.data()[ba.size()] = '\0';
5842 char16_t *dst = d.data();
5843
5844 qt_from_latin1(dst, ba.data(), size_t(ba.size()));
5845 }
5846 return QString(std::move(d));
5847}
5848
5849/*!
5850 \fn QString QString::fromLatin1(const char *str, qsizetype size)
5851 Returns a QString initialized with the first \a size characters
5852 of the Latin-1 string \a str.
5853
5854 If \a size is \c{-1}, \c{strlen(str)} is used instead.
5855
5856 \sa toLatin1(), fromUtf8(), fromLocal8Bit()
5857*/
5858
5859/*!
5860 \fn QString QString::fromLatin1(const QByteArray &str)
5861 \overload
5862 \since 5.0
5863
5864 Returns a QString initialized with the Latin-1 string \a str.
5865
5866 \note: any null ('\\0') bytes in the byte array will be included in this
5867 string, converted to Unicode null characters (U+0000). This behavior is
5868 different from Qt 5.x.
5869*/
5870
5871/*!
5872 \fn QString QString::fromLocal8Bit(const char *str, qsizetype size)
5873 Returns a QString initialized with the first \a size characters
5874 of the 8-bit string \a str.
5875
5876 If \a size is \c{-1}, \c{strlen(str)} is used instead.
5877
5878 \include qstring.qdocinc {qstring-local-8-bit-equivalent} {fromUtf8}
5879
5880 \sa toLocal8Bit(), fromLatin1(), fromUtf8()
5881*/
5882
5883/*!
5884 \fn QString QString::fromLocal8Bit(const QByteArray &str)
5885 \overload
5886 \since 5.0
5887
5888 Returns a QString initialized with the 8-bit string \a str.
5889
5890 \include qstring.qdocinc {qstring-local-8-bit-equivalent} {fromUtf8}
5891
5892 \note: any null ('\\0') bytes in the byte array will be included in this
5893 string, converted to Unicode null characters (U+0000). This behavior is
5894 different from Qt 5.x.
5895*/
5896
5897/*!
5898 \fn QString QString::fromLocal8Bit(QByteArrayView str)
5899 \overload
5900 \since 6.0
5901
5902 Returns a QString initialized with the 8-bit string \a str.
5903
5904 \include qstring.qdocinc {qstring-local-8-bit-equivalent} {fromUtf8}
5905
5906 \note: any null ('\\0') bytes in the byte array will be included in this
5907 string, converted to Unicode null characters (U+0000).
5908*/
5909QString QString::fromLocal8Bit(QByteArrayView ba)
5910{
5911 if (ba.isNull())
5912 return QString();
5913 if (ba.isEmpty())
5914 return QString(DataPointer::fromRawData(&_empty, 0));
5915 QStringDecoder toUtf16(QStringDecoder::System, QStringDecoder::Flag::Stateless);
5916 return toUtf16(ba);
5917}
5918
5919/*! \fn QString QString::fromUtf8(const char *str, qsizetype size)
5920 Returns a QString initialized with the first \a size bytes
5921 of the UTF-8 string \a str.
5922
5923 If \a size is \c{-1}, \c{strlen(str)} is used instead.
5924
5925 UTF-8 is a Unicode codec and can represent all characters in a Unicode
5926 string like QString. However, invalid sequences are possible with UTF-8
5927 and, if any such are found, they will be replaced with one or more
5928 "replacement characters", or suppressed. These include non-Unicode
5929 sequences, non-characters, overlong sequences or surrogate codepoints
5930 encoded into UTF-8.
5931
5932 This function can be used to process incoming data incrementally as long as
5933 all UTF-8 characters are terminated within the incoming data. Any
5934 unterminated characters at the end of the string will be replaced or
5935 suppressed. In order to do stateful decoding, please use \l QStringDecoder.
5936
5937 \sa toUtf8(), fromLatin1(), fromLocal8Bit()
5938*/
5939
5940/*!
5941 \fn QString QString::fromUtf8(const char8_t *str)
5942 \overload
5943 \since 6.1
5944
5945 This overload is only available when compiling in C++20 mode.
5946*/
5947
5948/*!
5949 \fn QString QString::fromUtf8(const char8_t *str, qsizetype size)
5950 \overload
5951 \since 6.0
5952
5953 This overload is only available when compiling in C++20 mode.
5954*/
5955
5956/*!
5957 \fn QString QString::fromUtf8(const QByteArray &str)
5958 \overload
5959 \since 5.0
5960
5961 Returns a QString initialized with the UTF-8 string \a str.
5962
5963 \note: any null ('\\0') bytes in the byte array will be included in this
5964 string, converted to Unicode null characters (U+0000). This behavior is
5965 different from Qt 5.x.
5966*/
5967
5968/*!
5969 \fn QString QString::fromUtf8(QByteArrayView str)
5970 \overload
5971 \since 6.0
5972
5973 Returns a QString initialized with the UTF-8 string \a str.
5974
5975 \note: any null ('\\0') bytes in the byte array will be included in this
5976 string, converted to Unicode null characters (U+0000).
5977*/
5978QString QString::fromUtf8(QByteArrayView ba)
5979{
5980 if (ba.isNull())
5981 return QString();
5982 if (ba.isEmpty())
5983 return QString(DataPointer::fromRawData(&_empty, 0));
5984 return QUtf8::convertToUnicode(ba);
5985}
5986
5987#ifndef QT_BOOTSTRAPPED
5988/*!
5989 \since 5.3
5990 Returns a QString initialized with the first \a size characters
5991 of the Unicode string \a unicode (ISO-10646-UTF-16 encoded).
5992
5993 If \a size is -1 (default), \a unicode must be '\\0'-terminated.
5994
5995 This function checks for a Byte Order Mark (BOM). If it is missing,
5996 host byte order is assumed.
5997
5998 This function is slow compared to the other Unicode conversions.
5999 Use QString(const QChar *, qsizetype) or QString(const QChar *) if possible.
6000
6001 QString makes a deep copy of the Unicode data.
6002
6003 \sa utf16(), setUtf16(), fromStdU16String()
6004*/
6005QString QString::fromUtf16(const char16_t *unicode, qsizetype size)
6006{
6007 if (!unicode)
6008 return QString();
6009 if (size < 0)
6010 size = QtPrivate::qustrlen(unicode);
6011 QStringDecoder toUtf16(QStringDecoder::Utf16, QStringDecoder::Flag::Stateless);
6012 return toUtf16(QByteArrayView(reinterpret_cast<const char *>(unicode), size * 2));
6013}
6014
6015/*!
6016 \fn QString QString::fromUtf16(const ushort *str, qsizetype size)
6017 \deprecated [6.0] Use the \c char16_t overload instead.
6018*/
6019
6020/*!
6021 \fn QString QString::fromUcs4(const uint *str, qsizetype size)
6022 \since 4.2
6023 \deprecated [6.0] Use the \c char32_t overload instead.
6024*/
6025
6026/*!
6027 \since 5.3
6028
6029 Returns a QString initialized with the first \a size characters
6030 of the Unicode string \a unicode (encoded as UTF-32).
6031
6032 If \a size is -1 (default), \a unicode must be '\\0'-terminated.
6033
6034 \sa toUcs4(), fromUtf16(), utf16(), setUtf16(), fromWCharArray(),
6035 fromStdU32String()
6036*/
6037QString QString::fromUcs4(const char32_t *unicode, qsizetype size)
6038{
6039 if (!unicode)
6040 return QString();
6041 if (size < 0) {
6042 if constexpr (sizeof(char32_t) == sizeof(wchar_t))
6043 size = wcslen(reinterpret_cast<const wchar_t *>(unicode));
6044 else
6045 size = std::char_traits<char32_t>::length(unicode);
6046 }
6047 QStringDecoder toUtf16(QStringDecoder::Utf32, QStringDecoder::Flag::Stateless);
6048 return toUtf16(QByteArrayView(reinterpret_cast<const char *>(unicode), size * 4));
6049}
6050#endif // !QT_BOOTSTRAPPED
6051
6052/*!
6053 Resizes the string to \a size characters and copies \a unicode
6054 into the string.
6055
6056 If \a unicode is \nullptr, nothing is copied, but the string is still
6057 resized to \a size.
6058
6059 \sa unicode(), setUtf16()
6060*/
6061QString& QString::setUnicode(const QChar *unicode, qsizetype size)
6062{
6063 resize(size);
6064 if (unicode && size)
6065 memcpy(d.data(), unicode, size * sizeof(QChar));
6066 return *this;
6067}
6068
6069/*!
6070 \fn QString::setUnicode(const char16_t *unicode, qsizetype size)
6071 \overload
6072 \since 6.9
6073
6074 \sa unicode(), setUtf16()
6075*/
6076
6077/*!
6078 \fn QString::setUtf16(const char16_t *unicode, qsizetype size)
6079 \since 6.9
6080
6081 Resizes the string to \a size characters and copies \a unicode
6082 into the string.
6083
6084 If \a unicode is \nullptr, nothing is copied, but the string is still
6085 resized to \a size.
6086
6087 Note that unlike fromUtf16(), this function does not consider BOMs and
6088 possibly differing byte ordering.
6089
6090 \sa utf16(), setUnicode()
6091*/
6092
6093/*!
6094 \fn QString &QString::setUtf16(const ushort *unicode, qsizetype size)
6095 \obsolete [6.10] Use the \c char16_t overload instead.
6096*/
6097
6098/*!
6099 \fn QString QString::simplified() const
6100
6101 Returns a string that has whitespace removed from the start
6102 and the end, and that has each sequence of internal whitespace
6103 replaced with a single space.
6104
6105 Whitespace means any character for which QChar::isSpace() returns
6106 \c true. This includes the ASCII characters '\\t', '\\n', '\\v',
6107 '\\f', '\\r', and ' '.
6108
6109 Example:
6110
6111 \snippet qstring/main.cpp 57
6112
6113 \sa trimmed()
6114*/
6115QString QString::simplified_helper(const QString &str)
6116{
6117 return QStringAlgorithms<const QString>::simplified_helper(str);
6118}
6119
6120QString QString::simplified_helper(QString &str)
6121{
6122 return QStringAlgorithms<QString>::simplified_helper(str);
6123}
6124
6125namespace {
6126 template <typename StringView>
6127 StringView qt_trimmed(StringView s) noexcept
6128 {
6129 const auto [begin, end] = QStringAlgorithms<const StringView>::trimmed_helper_positions(s);
6130 return StringView{begin, end};
6131 }
6132}
6133
6134/*!
6135 \fn QStringView QtPrivate::trimmed(QStringView s)
6136 \fn QLatin1StringView QtPrivate::trimmed(QLatin1StringView s)
6137 \internal
6138 \relates QStringView
6139 \since 5.10
6140
6141 Returns \a s with whitespace removed from the start and the end.
6142
6143 Whitespace means any character for which QChar::isSpace() returns
6144 \c true. This includes the ASCII characters '\\t', '\\n', '\\v',
6145 '\\f', '\\r', and ' '.
6146
6147 \sa QString::trimmed(), QStringView::trimmed(), QLatin1StringView::trimmed()
6148*/
6149QStringView QtPrivate::trimmed(QStringView s) noexcept
6150{
6151 return qt_trimmed(s);
6152}
6153
6154QLatin1StringView QtPrivate::trimmed(QLatin1StringView s) noexcept
6155{
6156 return qt_trimmed(s);
6157}
6158
6159/*!
6160 \fn QString QString::trimmed() const
6161
6162 Returns a string that has whitespace removed from the start and
6163 the end.
6164
6165 Whitespace means any character for which QChar::isSpace() returns
6166 \c true. This includes the ASCII characters '\\t', '\\n', '\\v',
6167 '\\f', '\\r', and ' '.
6168
6169 Example:
6170
6171 \snippet qstring/main.cpp 82
6172
6173 Unlike simplified(), trimmed() leaves internal whitespace alone.
6174
6175 \sa simplified()
6176*/
6177QString QString::trimmed_helper(const QString &str)
6178{
6179 return QStringAlgorithms<const QString>::trimmed_helper(str);
6180}
6181
6182QString QString::trimmed_helper(QString &str)
6183{
6184 return QStringAlgorithms<QString>::trimmed_helper(str);
6185}
6186
6187/*! \fn const QChar QString::at(qsizetype position) const
6188
6189 Returns the character at the given index \a position in the
6190 string.
6191
6192 The \a position must be a valid index position in the string
6193 (i.e., 0 <= \a position < size()).
6194
6195 \sa operator[]()
6196*/
6197
6198/*!
6199 \fn QChar &QString::operator[](qsizetype position)
6200
6201 Returns the character at the specified \a position in the string as a
6202 modifiable reference.
6203
6204 Example:
6205
6206 \snippet qstring/main.cpp 85
6207
6208 \sa at()
6209*/
6210
6211/*!
6212 \fn const QChar QString::operator[](qsizetype position) const
6213
6214 \overload operator[]()
6215*/
6216
6217/*!
6218 \fn QChar QString::front() const
6219 \since 5.10
6220
6221 Returns the first character in the string.
6222 Same as \c{at(0)}.
6223
6224 This function is provided for STL compatibility.
6225
6226 \warning Calling this function on an empty string constitutes
6227 undefined behavior.
6228
6229 \sa back(), at(), operator[]()
6230*/
6231
6232/*!
6233 \fn QChar QString::back() const
6234 \since 5.10
6235
6236 Returns the last character in the string.
6237 Same as \c{at(size() - 1)}.
6238
6239 This function is provided for STL compatibility.
6240
6241 \warning Calling this function on an empty string constitutes
6242 undefined behavior.
6243
6244 \sa front(), at(), operator[]()
6245*/
6246
6247/*!
6248 \fn QChar &QString::front()
6249 \since 5.10
6250
6251 Returns a reference to the first character in the string.
6252 Same as \c{operator[](0)}.
6253
6254 This function is provided for STL compatibility.
6255
6256 \warning Calling this function on an empty string constitutes
6257 undefined behavior.
6258
6259 \sa back(), at(), operator[]()
6260*/
6261
6262/*!
6263 \fn QChar &QString::back()
6264 \since 5.10
6265
6266 Returns a reference to the last character in the string.
6267 Same as \c{operator[](size() - 1)}.
6268
6269 This function is provided for STL compatibility.
6270
6271 \warning Calling this function on an empty string constitutes
6272 undefined behavior.
6273
6274 \sa front(), at(), operator[]()
6275*/
6276
6277/*!
6278 \fn void QString::truncate(qsizetype position)
6279
6280 Truncates the string starting from, and including, the element at index
6281 \a position.
6282
6283 If the specified \a position index is beyond the end of the
6284 string, nothing happens.
6285
6286 Example:
6287
6288 \snippet qstring/main.cpp 83
6289
6290 If \a position is negative, it is equivalent to passing zero.
6291
6292 \sa chop(), resize(), first(), QStringView::truncate()
6293*/
6294
6295void QString::truncate(qsizetype pos)
6296{
6297 if (pos < size())
6298 resize(pos);
6299}
6300
6301
6302/*!
6303 Removes \a n characters from the end of the string.
6304
6305 If \a n is greater than or equal to size(), the result is an
6306 empty string; if \a n is negative, it is equivalent to passing zero.
6307
6308 Example:
6309 \snippet qstring/main.cpp 15
6310
6311 If you want to remove characters from the \e beginning of the
6312 string, use remove() instead.
6313
6314 \sa truncate(), resize(), remove(), QStringView::chop()
6315*/
6316void QString::chop(qsizetype n)
6317{
6318 if (n > size())
6319 resize(0); // can't remove more than size() characters
6320 else if (n > 0)
6321 resize(d.size - n);
6322}
6323
6324/*!
6325 Sets every character in the string to character \a ch.
6326
6327 Example:
6328
6329 \snippet qstring/main.cpp fill
6330
6331 \sa resize()
6332*/
6333QString& QString::fill(QChar ch)
6334{
6335 QChar *ptr = begin();
6336 std::fill_n(ptr, size(), ch.unicode());
6337 return *this;
6338}
6339
6340/*!
6341 \overload
6342 Sets every character in the string to character \a ch. If \a size is
6343 negative, the string's current size is retained; otherwise, the string is
6344 resized to size \a size beforehand.
6345
6346 Example:
6347
6348 \snippet qstring/main.cpp 21
6349
6350 \sa resize()
6351*/
6352
6353QString& QString::fill(QChar ch, qsizetype size)
6354{
6355 if (size >= 0)
6356 resizeForOverwrite(size);
6357 return fill(ch);
6358}
6359
6360/*!
6361 \fn qsizetype QString::length() const
6362
6363 Returns the number of characters in this string. Equivalent to
6364 size().
6365
6366 \sa resize()
6367*/
6368
6369/*!
6370 \fn qsizetype QString::size() const
6371
6372 Returns the number of characters in this string.
6373
6374 The last character in the string is at position size() - 1.
6375
6376 Example:
6377 \snippet qstring/main.cpp 58
6378
6379 \sa isEmpty(), resize()
6380*/
6381
6382/*!
6383 \fn qsizetype QString::max_size() const
6384 \fn qsizetype QString::maxSize()
6385 \since 6.8
6386
6387 It returns the maximum number of elements that the string can
6388 theoretically hold. In practice, the number can be much smaller,
6389 limited by the amount of memory available to the system.
6390*/
6391
6392/*! \fn bool QString::isNull() const
6393
6394 Returns \c true if this string is null; otherwise returns \c false.
6395
6396 Example:
6397
6398 \snippet qstring/main.cpp 28
6399
6400 Qt makes a distinction between null strings and empty strings for
6401 historical reasons. For most applications, what matters is
6402 whether or not a string contains any data, and this can be
6403 determined using the isEmpty() function.
6404
6405 \sa isEmpty()
6406*/
6407
6408/*! \fn bool QString::isEmpty() const
6409
6410 Returns \c true if the string has no characters; otherwise returns
6411 \c false.
6412
6413 Example:
6414
6415 \snippet qstring/main.cpp 27
6416
6417 \sa size()
6418*/
6419
6420/*! \fn QString &QString::operator+=(const QString &other)
6421
6422 Appends the string \a other onto the end of this string and
6423 returns a reference to this string.
6424
6425 Example:
6426
6427 \snippet qstring/main.cpp 84
6428
6429 This operation is typically very fast (\l{constant time}),
6430 because QString preallocates extra space at the end of the string
6431 data so it can grow without reallocating the entire string each
6432 time.
6433
6434 \sa append(), prepend()
6435*/
6436
6437/*! \fn QString &QString::operator+=(QLatin1StringView str)
6438
6439 \overload operator+=()
6440
6441 Appends the Latin-1 string viewed by \a str to this string.
6442*/
6443
6444/*! \fn QString &QString::operator+=(QUtf8StringView str)
6445 \since 6.5
6446 \overload operator+=()
6447
6448 Appends the UTF-8 string view \a str to this string.
6449*/
6450
6451/*! \fn QString &QString::operator+=(const QByteArray &ba)
6452
6453 \overload operator+=()
6454
6455 Appends the byte array \a ba to this string. The byte array is converted
6456 to Unicode using the fromUtf8() function. If any NUL characters ('\\0')
6457 are embedded in the \a ba byte array, they will be included in the
6458 transformation.
6459
6460 You can disable this function by defining
6461 \l QT_NO_CAST_FROM_ASCII when you compile your applications. This
6462 can be useful if you want to ensure that all user-visible strings
6463 go through QObject::tr(), for example.
6464*/
6465
6466/*! \fn QString &QString::operator+=(const char *str)
6467
6468 \overload operator+=()
6469
6470 Appends the string \a str to this string. The const char pointer
6471 is converted to Unicode using the fromUtf8() function.
6472
6473 You can disable this function by defining \l QT_NO_CAST_FROM_ASCII
6474 when you compile your applications. This can be useful if you want
6475 to ensure that all user-visible strings go through QObject::tr(),
6476 for example.
6477*/
6478
6479/*! \fn QString &QString::operator+=(QStringView str)
6480 \since 6.0
6481 \overload operator+=()
6482
6483 Appends the string view \a str to this string.
6484*/
6485
6486/*! \fn QString &QString::operator+=(QChar ch)
6487
6488 \overload operator+=()
6489
6490 Appends the character \a ch to the string.
6491*/
6492
6493/*!
6494 \fn bool QString::operator==(const char * const &lhs, const QString &rhs)
6495
6496 \overload operator==()
6497
6498 Returns \c true if \a lhs is equal to \a rhs; otherwise returns \c false.
6499 Note that no string is equal to \a lhs being 0.
6500
6501 Equivalent to \c {lhs != 0 && compare(lhs, rhs) == 0}.
6502*/
6503
6504/*!
6505 \fn bool QString::operator!=(const char * const &lhs, const QString &rhs)
6506
6507 Returns \c true if \a lhs is not equal to \a rhs; otherwise returns
6508 \c false.
6509
6510 For \a lhs != 0, this is equivalent to \c {compare(} \a lhs, \a rhs
6511 \c {) != 0}. Note that no string is equal to \a lhs being 0.
6512*/
6513
6514/*!
6515 \fn bool QString::operator<(const char * const &lhs, const QString &rhs)
6516
6517 Returns \c true if \a lhs is lexically less than \a rhs; otherwise
6518 returns \c false. For \a lhs != 0, this is equivalent to \c
6519 {compare(lhs, rhs) < 0}.
6520
6521 \sa {Comparing Strings}
6522*/
6523
6524/*!
6525 \fn bool QString::operator<=(const char * const &lhs, const QString &rhs)
6526
6527 Returns \c true if \a lhs is lexically less than or equal to \a rhs;
6528 otherwise returns \c false. For \a lhs != 0, this is equivalent to \c
6529 {compare(lhs, rhs) <= 0}.
6530
6531 \sa {Comparing Strings}
6532*/
6533
6534/*!
6535 \fn bool QString::operator>(const char * const &lhs, const QString &rhs)
6536
6537 Returns \c true if \a lhs is lexically greater than \a rhs; otherwise
6538 returns \c false. Equivalent to \c {compare(lhs, rhs) > 0}.
6539
6540 \sa {Comparing Strings}
6541*/
6542
6543/*!
6544 \fn bool QString::operator>=(const char * const &lhs, const QString &rhs)
6545
6546 Returns \c true if \a lhs is lexically greater than or equal to \a rhs;
6547 otherwise returns \c false. For \a lhs != 0, this is equivalent to \c
6548 {compare(lhs, rhs) >= 0}.
6549
6550 \sa {Comparing Strings}
6551*/
6552
6553/*!
6554 \fn QString operator+(const QString &s1, const QString &s2)
6555 \fn QString operator+(QString &&s1, const QString &s2)
6556 \relates QString
6557
6558 Returns a string which is the result of concatenating \a s1 and \a
6559 s2.
6560*/
6561
6562/*!
6563 \fn QString operator+(const QString &s1, const char *s2)
6564 \relates QString
6565
6566 Returns a string which is the result of concatenating \a s1 and \a
6567 s2 (\a s2 is converted to Unicode using the QString::fromUtf8()
6568 function).
6569
6570 \sa QString::fromUtf8()
6571*/
6572
6573/*!
6574 \fn QString operator+(const char *s1, const QString &s2)
6575 \relates QString
6576
6577 Returns a string which is the result of concatenating \a s1 and \a
6578 s2 (\a s1 is converted to Unicode using the QString::fromUtf8()
6579 function).
6580
6581 \sa QString::fromUtf8()
6582*/
6583
6584/*!
6585 \fn QString operator+(QStringView lhs, const QString &rhs)
6586 \fn QString operator+(const QString &lhs, QStringView rhs)
6587
6588 \relates QString
6589 \since 6.9
6590
6591 Returns a string that is the result of concatenating \a lhs and \a rhs.
6592*/
6593
6594/*!
6595 \fn int QString::compare(const QString &s1, const QString &s2, Qt::CaseSensitivity cs)
6596 \since 4.2
6597
6598 Compares the string \a s1 with the string \a s2 and returns a negative integer
6599 if \a s1 is less than \a s2, a positive integer if it is greater than \a s2,
6600 and zero if they are equal.
6601
6602 \include qstring.qdocinc {search-comparison-case-sensitivity} {comparison}
6603
6604 Case sensitive comparison is based exclusively on the numeric
6605 Unicode values of the characters and is very fast, but is not what
6606 a human would expect. Consider sorting user-visible strings with
6607 localeAwareCompare().
6608
6609 \snippet qstring/main.cpp 16
6610
6611//! [compare-isNull-vs-isEmpty]
6612 \note This function treats null strings the same as empty strings,
6613 for more details see \l {Distinction Between Null and Empty Strings}.
6614//! [compare-isNull-vs-isEmpty]
6615
6616 \sa operator==(), operator<(), operator>(), {Comparing Strings}
6617*/
6618
6619/*!
6620 \fn int QString::compare(const QString &s1, QLatin1StringView s2, Qt::CaseSensitivity cs)
6621 \since 4.2
6622 \overload compare()
6623
6624 Performs a comparison of \a s1 and \a s2, using the case
6625 sensitivity setting \a cs.
6626*/
6627
6628/*!
6629 \fn int QString::compare(QLatin1StringView s1, const QString &s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
6630
6631 \since 4.2
6632 \overload compare()
6633
6634 Performs a comparison of \a s1 and \a s2, using the case
6635 sensitivity setting \a cs.
6636*/
6637
6638/*!
6639 \fn int QString::compare(QStringView s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
6640
6641 \since 5.12
6642 \overload compare()
6643
6644 Performs a comparison of this with \a s, using the case
6645 sensitivity setting \a cs.
6646*/
6647
6648/*!
6649 \fn int QString::compare(QChar ch, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
6650
6651 \since 5.14
6652 \overload compare()
6653
6654 Performs a comparison of this with \a ch, using the case
6655 sensitivity setting \a cs.
6656*/
6657
6658/*!
6659 \overload compare()
6660 \since 4.2
6661
6662 Lexically compares this string with the string \a other and returns
6663 a negative integer if this string is less than \a other, a positive
6664 integer if it is greater than \a other, and zero if they are equal.
6665
6666 Same as compare(*this, \a other, \a cs).
6667*/
6668int QString::compare(const QString &other, Qt::CaseSensitivity cs) const noexcept
6669{
6670 return QtPrivate::compareStrings(*this, other, cs);
6671}
6672
6673/*!
6674 \internal
6675 \since 4.5
6676*/
6677int QString::compare_helper(const QChar *data1, qsizetype length1, const QChar *data2, qsizetype length2,
6678 Qt::CaseSensitivity cs) noexcept
6679{
6680 Q_ASSERT(length1 >= 0);
6681 Q_ASSERT(length2 >= 0);
6682 Q_ASSERT(data1 || length1 == 0);
6683 Q_ASSERT(data2 || length2 == 0);
6684 return QtPrivate::compareStrings(QStringView(data1, length1), QStringView(data2, length2), cs);
6685}
6686
6687/*!
6688 \overload compare()
6689 \since 4.2
6690
6691 Same as compare(*this, \a other, \a cs).
6692*/
6693int QString::compare(QLatin1StringView other, Qt::CaseSensitivity cs) const noexcept
6694{
6695 return QtPrivate::compareStrings(*this, other, cs);
6696}
6697
6698/*!
6699 \internal
6700 \since 5.0
6701*/
6702int QString::compare_helper(const QChar *data1, qsizetype length1, const char *data2, qsizetype length2,
6703 Qt::CaseSensitivity cs) noexcept
6704{
6705 Q_ASSERT(length1 >= 0);
6706 Q_ASSERT(data1 || length1 == 0);
6707 if (!data2)
6708 return qt_lencmp(length1, 0);
6709 if (Q_UNLIKELY(length2 < 0))
6710 length2 = qsizetype(strlen(data2));
6711 return QtPrivate::compareStrings(QStringView(data1, length1),
6712 QUtf8StringView(data2, length2), cs);
6713}
6714
6715/*!
6716 \fn int QString::compare(const QString &s1, QStringView s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
6717 \overload compare()
6718*/
6719
6720/*!
6721 \fn int QString::compare(QStringView s1, const QString &s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
6722 \overload compare()
6723*/
6724
6725bool comparesEqual(const QByteArrayView &lhs, const QChar &rhs) noexcept
6726{
6727 return QtPrivate::equalStrings(QUtf8StringView(lhs), QStringView(&rhs, 1));
6728}
6729
6730Qt::strong_ordering compareThreeWay(const QByteArrayView &lhs, const QChar &rhs) noexcept
6731{
6732 const int res = QtPrivate::compareStrings(QUtf8StringView(lhs), QStringView(&rhs, 1));
6733 return Qt::compareThreeWay(res, 0);
6734}
6735
6736bool comparesEqual(const QByteArrayView &lhs, char16_t rhs) noexcept
6737{
6738 return QtPrivate::equalStrings(QUtf8StringView(lhs), QStringView(&rhs, 1));
6739}
6740
6741Qt::strong_ordering compareThreeWay(const QByteArrayView &lhs, char16_t rhs) noexcept
6742{
6743 const int res = QtPrivate::compareStrings(QUtf8StringView(lhs), QStringView(&rhs, 1));
6744 return Qt::compareThreeWay(res, 0);
6745}
6746
6747bool comparesEqual(const QByteArray &lhs, const QChar &rhs) noexcept
6748{
6749 return QtPrivate::equalStrings(QUtf8StringView(lhs), QStringView(&rhs, 1));
6750}
6751
6752Qt::strong_ordering compareThreeWay(const QByteArray &lhs, const QChar &rhs) noexcept
6753{
6754 const int res = QtPrivate::compareStrings(QUtf8StringView(lhs), QStringView(&rhs, 1));
6755 return Qt::compareThreeWay(res, 0);
6756}
6757
6758bool comparesEqual(const QByteArray &lhs, char16_t rhs) noexcept
6759{
6760 return QtPrivate::equalStrings(QUtf8StringView(lhs), QStringView(&rhs, 1));
6761}
6762
6763Qt::strong_ordering compareThreeWay(const QByteArray &lhs, char16_t rhs) noexcept
6764{
6765 const int res = QtPrivate::compareStrings(QUtf8StringView(lhs), QStringView(&rhs, 1));
6766 return Qt::compareThreeWay(res, 0);
6767}
6768
6769/*!
6770 \internal
6771 \since 6.8
6772*/
6773bool QT_FASTCALL QChar::equal_helper(QChar lhs, const char *rhs) noexcept
6774{
6775 return QtPrivate::equalStrings(QStringView(&lhs, 1), QUtf8StringView(rhs));
6776}
6777
6778int QT_FASTCALL QChar::compare_helper(QChar lhs, const char *rhs) noexcept
6779{
6780 return QtPrivate::compareStrings(QStringView(&lhs, 1), QUtf8StringView(rhs));
6781}
6782
6783/*!
6784 \internal
6785 \since 6.8
6786*/
6787bool QStringView::equal_helper(QStringView sv, const char *data, qsizetype len)
6788{
6789 Q_ASSERT(len >= 0);
6790 Q_ASSERT(data || len == 0);
6791 return QtPrivate::equalStrings(sv, QUtf8StringView(data, len));
6792}
6793
6794/*!
6795 \internal
6796 \since 6.8
6797*/
6798int QStringView::compare_helper(QStringView sv, const char *data, qsizetype len)
6799{
6800 Q_ASSERT(len >= 0);
6801 Q_ASSERT(data || len == 0);
6802 return QtPrivate::compareStrings(sv, QUtf8StringView(data, len));
6803}
6804
6805/*!
6806 \internal
6807 \since 6.8
6808*/
6809bool QLatin1StringView::equal_helper(QLatin1StringView s1, const char *s2, qsizetype len) noexcept
6810{
6811 // because qlatin1stringview.h can't include qutf8stringview.h
6812 Q_ASSERT(len >= 0);
6813 Q_ASSERT(s2 || len == 0);
6814 return QtPrivate::equalStrings(s1, QUtf8StringView(s2, len));
6815}
6816
6817/*!
6818 \internal
6819 \since 6.6
6820*/
6821int QLatin1StringView::compare_helper(const QLatin1StringView &s1, const char *s2, qsizetype len) noexcept
6822{
6823 // because qlatin1stringview.h can't include qutf8stringview.h
6824 Q_ASSERT(len >= 0);
6825 Q_ASSERT(s2 || len == 0);
6826 return QtPrivate::compareStrings(s1, QUtf8StringView(s2, len));
6827}
6828
6829/*!
6830 \internal
6831 \since 4.5
6832*/
6833int QLatin1StringView::compare_helper(const QChar *data1, qsizetype length1, QLatin1StringView s2,
6834 Qt::CaseSensitivity cs) noexcept
6835{
6836 Q_ASSERT(length1 >= 0);
6837 Q_ASSERT(data1 || length1 == 0);
6838 return QtPrivate::compareStrings(QStringView(data1, length1), s2, cs);
6839}
6840
6841/*!
6842 \fn int QString::localeAwareCompare(const QString & s1, const QString & s2)
6843
6844 Compares \a s1 with \a s2 and returns an integer less than, equal
6845 to, or greater than zero if \a s1 is less than, equal to, or
6846 greater than \a s2.
6847
6848 The comparison is performed in a locale- and also
6849 platform-dependent manner. Use this function to present sorted
6850 lists of strings to the user.
6851
6852 \sa compare(), QLocale, {Comparing Strings}
6853*/
6854
6855/*!
6856 \fn int QString::localeAwareCompare(QStringView other) const
6857 \since 6.0
6858 \overload localeAwareCompare()
6859
6860 Compares this string with the \a other string and returns an
6861 integer less than, equal to, or greater than zero if this string
6862 is less than, equal to, or greater than the \a other string.
6863
6864 The comparison is performed in a locale- and also
6865 platform-dependent manner. Use this function to present sorted
6866 lists of strings to the user.
6867
6868 Same as \c {localeAwareCompare(*this, other)}.
6869
6870 \sa {Comparing Strings}
6871*/
6872
6873/*!
6874 \fn int QString::localeAwareCompare(QStringView s1, QStringView s2)
6875 \since 6.0
6876 \overload localeAwareCompare()
6877
6878 Compares \a s1 with \a s2 and returns an integer less than, equal
6879 to, or greater than zero if \a s1 is less than, equal to, or
6880 greater than \a s2.
6881
6882 The comparison is performed in a locale- and also
6883 platform-dependent manner. Use this function to present sorted
6884 lists of strings to the user.
6885
6886 \sa {Comparing Strings}
6887*/
6888
6889
6890#if !defined(CSTR_LESS_THAN)
6891#define CSTR_LESS_THAN 1
6892#define CSTR_EQUAL 2
6893#define CSTR_GREATER_THAN 3
6894#endif
6895
6896/*!
6897 \overload localeAwareCompare()
6898
6899 Compares this string with the \a other string and returns an
6900 integer less than, equal to, or greater than zero if this string
6901 is less than, equal to, or greater than the \a other string.
6902
6903 The comparison is performed in a locale- and also
6904 platform-dependent manner. Use this function to present sorted
6905 lists of strings to the user.
6906
6907 Same as \c {localeAwareCompare(*this, other)}.
6908
6909 \sa {Comparing Strings}
6910*/
6911int QString::localeAwareCompare(const QString &other) const
6912{
6913 return localeAwareCompare_helper(constData(), size(), other.constData(), other.size());
6914}
6915
6916/*!
6917 \internal
6918 \since 4.5
6919*/
6920int QString::localeAwareCompare_helper(const QChar *data1, qsizetype length1,
6921 const QChar *data2, qsizetype length2)
6922{
6923 Q_ASSERT(length1 >= 0);
6924 Q_ASSERT(data1 || length1 == 0);
6925 Q_ASSERT(length2 >= 0);
6926 Q_ASSERT(data2 || length2 == 0);
6927
6928 // do the right thing for null and empty
6929 if (length1 == 0 || length2 == 0)
6930 return QtPrivate::compareStrings(QStringView(data1, length1), QStringView(data2, length2),
6931 Qt::CaseSensitive);
6932
6933#if QT_CONFIG(icu) || defined(Q_OS_ANDROID)
6934 return QCollator::defaultCompare(QStringView(data1, length1), QStringView(data2, length2));
6935#else
6936 const QString lhs = QString::fromRawData(data1, length1).normalized(QString::NormalizationForm_C);
6937 const QString rhs = QString::fromRawData(data2, length2).normalized(QString::NormalizationForm_C);
6938# if defined(Q_OS_WIN)
6939 int res = CompareStringEx(LOCALE_NAME_USER_DEFAULT, 0, (LPWSTR)lhs.constData(), lhs.length(), (LPWSTR)rhs.constData(), rhs.length(), NULL, NULL, 0);
6940
6941 switch (res) {
6942 case CSTR_LESS_THAN:
6943 return -1;
6944 case CSTR_GREATER_THAN:
6945 return 1;
6946 default:
6947 return 0;
6948 }
6949# elif defined (Q_OS_DARWIN)
6950 // Use CFStringCompare for comparing strings on Mac. This makes Qt order
6951 // strings the same way as native applications do, and also respects
6952 // the "Order for sorted lists" setting in the International preferences
6953 // panel.
6954 const CFStringRef thisString =
6955 CFStringCreateWithCharactersNoCopy(kCFAllocatorDefault,
6956 reinterpret_cast<const UniChar *>(lhs.constData()), lhs.length(), kCFAllocatorNull);
6957 const CFStringRef otherString =
6958 CFStringCreateWithCharactersNoCopy(kCFAllocatorDefault,
6959 reinterpret_cast<const UniChar *>(rhs.constData()), rhs.length(), kCFAllocatorNull);
6960
6961 const int result = CFStringCompare(thisString, otherString, kCFCompareLocalized);
6962 CFRelease(thisString);
6963 CFRelease(otherString);
6964 return result;
6965# elif defined(Q_OS_UNIX)
6966 // declared in <string.h> (no better than QtPrivate::compareStrings() on Android, sadly)
6967 return strcoll(lhs.toLocal8Bit().constData(), rhs.toLocal8Bit().constData());
6968# else
6969# error "This case shouldn't happen"
6970 return QtPrivate::compareStrings(lhs, rhs, Qt::CaseSensitive);
6971# endif
6972#endif // !QT_CONFIG(icu)
6973}
6974
6975
6976/*!
6977 \fn const QChar *QString::unicode() const
6978
6979 Returns a Unicode representation of the string.
6980 The result remains valid until the string is modified.
6981
6982 \note The returned string may not be '\\0'-terminated.
6983 Use size() to determine the length of the array.
6984
6985 \sa utf16(), fromRawData()
6986*/
6987
6988/*!
6989 \fn const ushort *QString::utf16() const
6990 \obsolete [6.11] Use nullTerminate() and cast data() to \c{const char16_t *}.
6991
6992 Returns the QString as a '\\0\'-terminated array of unsigned
6993 shorts. The result remains valid until the string is modified.
6994
6995 The returned string is in host byte order.
6996
6997 \sa unicode()
6998*/
6999
7000const ushort *QString::utf16() const
7001{
7002 if (!d.isMutable()) {
7003 // ensure '\0'-termination for ::fromRawData strings
7004 const_cast<QString*>(this)->reallocData(d.size, QArrayData::KeepSize);
7005 }
7006 return reinterpret_cast<const ushort *>(d.data());
7007}
7008
7009/*!
7010 \fn QString &QString::nullTerminate()
7011 \since 6.10
7012
7013 If this string data isn't null-terminated, this method will make a deep
7014 copy of the data and make it null-terminated.
7015
7016 A QString is null-terminated by default, however in some cases (e.g.
7017 when using fromRawData()), the string data doesn't necessarily end
7018 with a \c {\0} character, which could be a problem when calling methods
7019 that expect a null-terminated string.
7020
7021 \sa nullTerminated(), fromRawData(), setRawData()
7022*/
7023QString &QString::nullTerminate()
7024{
7025 // ensure '\0'-termination for ::fromRawData strings
7026 if (!d.isMutable())
7027 *this = QString{constData(), size()};
7028 return *this;
7029}
7030
7031/*!
7032 \fn QString QString::nullTerminated() const &
7033 \fn QString QString::nullTerminated() &&
7034 \since 6.10
7035
7036 Returns a copy of this string that is always null-terminated.
7037
7038 \sa nullTerminate(), fromRawData(), setRawData()
7039*/
7040QString QString::nullTerminated() const &
7041{
7042 // ensure '\0'-termination for ::fromRawData strings
7043 if (!d.isMutable())
7044 return QString{constData(), size()};
7045 return *this;
7046}
7047
7048QString QString::nullTerminated() &&
7049{
7050 nullTerminate();
7051 return std::move(*this);
7052}
7053
7054/*!
7055 Returns a string of size \a width that contains this string
7056 padded by the \a fill character.
7057
7058 If \a truncate is \c false and the size() of the string is more than
7059 \a width, then the returned string is a copy of the string.
7060
7061 \snippet qstring/main.cpp 32
7062
7063 If \a truncate is \c true and the size() of the string is more than
7064 \a width, then any characters in a copy of the string after
7065 position \a width are removed, and the copy is returned.
7066
7067 \snippet qstring/main.cpp 33
7068
7069 \sa rightJustified()
7070*/
7071
7072QString QString::leftJustified(qsizetype width, QChar fill, bool truncate) const
7073{
7074 return QStringAlgorithms<QString>::aligned(*this, width, fill, Qt::AlignLeft, truncate);
7075}
7076
7077/*!
7078 Returns a string of size() \a width that contains the \a fill
7079 character followed by the string. For example:
7080
7081 \snippet qstring/main.cpp 49
7082
7083 If \a truncate is \c false and the size() of the string is more than
7084 \a width, then the returned string is a copy of the string.
7085
7086 If \a truncate is true and the size() of the string is more than
7087 \a width, then the resulting string is truncated at position \a
7088 width.
7089
7090 \snippet qstring/main.cpp 50
7091
7092 \sa leftJustified()
7093*/
7094
7095QString QString::rightJustified(qsizetype width, QChar fill, bool truncate) const
7096{
7097 return QStringAlgorithms<QString>::aligned(*this, width, fill, Qt::AlignRight, truncate);
7098}
7099
7100/*!
7101 \fn QString QString::toLower() const
7102
7103 Returns a lowercase copy of the string.
7104
7105 \snippet qstring/main.cpp 75
7106
7107 The case conversion will always happen in the 'C' locale. For
7108 locale-dependent case folding use QLocale::toLower()
7109
7110 \sa toUpper(), QLocale::toLower()
7111*/
7112
7113namespace QUnicodeTables {
7114/*
7115 \internal
7116 Converts the \a str string starting from the position pointed to by the \a
7117 it iterator, using the Unicode case traits \c Traits, and returns the
7118 result. The input string must not be empty (the convertCase function below
7119 guarantees that).
7120
7121 The string type \c{T} is also a template and is either \c{const QString} or
7122 \c{QString}. This function can do both copy-conversion and in-place
7123 conversion depending on the state of the \a str parameter:
7124 \list
7125 \li \c{T} is \c{const QString}: copy-convert
7126 \li \c{T} is \c{QString} and its refcount != 1: copy-convert
7127 \li \c{T} is \c{QString} and its refcount == 1: in-place convert
7128 \endlist
7129
7130 In copy-convert mode, the local variable \c{s} is detached from the input
7131 \a str. In the in-place convert mode, \a str is in moved-from state and
7132 \c{s} contains the only copy of the string, without reallocation (thus,
7133 \a it is still valid).
7134
7135 There is one pathological case left: when the in-place conversion needs to
7136 reallocate memory to grow the buffer. In that case, we need to adjust the \a
7137 it pointer.
7138 */
7139template <typename T>
7140Q_NEVER_INLINE
7142{
7143 Q_ASSERT(!str.isEmpty());
7144 QString s = std::move(str); // will copy if T is const QString
7145 QChar *pp = s.begin() + it.index(); // will detach if necessary
7146
7147 do {
7148 const auto folded = fullConvertCase(it.next(), which);
7149 if (Q_UNLIKELY(folded.size() > 1)) {
7150 if (folded.chars[0] == *pp && folded.size() == 2) {
7151 // special case: only second actually changed (e.g. surrogate pairs),
7152 // avoid slow case
7153 ++pp;
7154 *pp++ = folded.chars[1];
7155 } else {
7156 // slow path: the string is growing
7157 qsizetype inpos = it.index() - 1;
7159
7160 s.replace(outpos, 1, reinterpret_cast<const QChar *>(folded.data()), folded.size());
7161 pp = const_cast<QChar *>(s.constBegin()) + outpos + folded.size();
7162
7163 // Adjust the input iterator if we are performing an in-place conversion
7164 if constexpr (!std::is_const<T>::value)
7166 }
7167 } else {
7168 *pp++ = folded.chars[0];
7169 }
7170 } while (it.hasNext());
7171
7172 return s;
7173}
7174
7175template <typename T>
7176static QString convertCase(T &str, QUnicodeTables::Case which)
7177{
7178 const QChar *p = str.constBegin();
7179 const QChar *e = p + str.size();
7180
7181 // this avoids out of bounds check in the loop
7182 while (e != p && e[-1].isHighSurrogate())
7183 --e;
7184
7185 QStringIterator it(p, e);
7186 while (it.hasNext()) {
7187 const char32_t uc = it.next();
7188 if (caseConversion(uc)[which].diff) {
7189 it.recede();
7190 return detachAndConvertCase(str, it, which);
7191 }
7192 }
7193 return std::move(str);
7194}
7195} // namespace QUnicodeTables
7196
7197QString QString::toLower_helper(const QString &str)
7198{
7199 return QUnicodeTables::convertCase(str, QUnicodeTables::LowerCase);
7200}
7201
7202QString QString::toLower_helper(QString &str)
7203{
7204 return QUnicodeTables::convertCase(str, QUnicodeTables::LowerCase);
7205}
7206
7207/*!
7208 \fn QString QString::toCaseFolded() const
7209
7210 Returns the case folded equivalent of the string. For most Unicode
7211 characters this is the same as toLower().
7212*/
7213
7214QString QString::toCaseFolded_helper(const QString &str)
7215{
7216 return QUnicodeTables::convertCase(str, QUnicodeTables::CaseFold);
7217}
7218
7219QString QString::toCaseFolded_helper(QString &str)
7220{
7221 return QUnicodeTables::convertCase(str, QUnicodeTables::CaseFold);
7222}
7223
7224/*!
7225 \fn QString QString::toUpper() const
7226
7227 Returns an uppercase copy of the string.
7228
7229 \snippet qstring/main.cpp 81
7230
7231 The case conversion will always happen in the 'C' locale. For
7232 locale-dependent case folding use QLocale::toUpper().
7233
7234 \note In some cases the uppercase form of a string may be longer than the
7235 original.
7236
7237 \note Since 2024, the German language officially prefers to uppercase ß
7238 (U+00DF LATIN SMALL LETTER SHARP S) as ẞ (U+1E9E LATIN CAPITAL LETTER SHARP S).
7239 Qt's implementation follows Unicode, which still mandates the use of "SS".
7240 If you need to implement the new German rules, you need to manually do
7241 \c{replace(u'ß', u'ẞ')} \e{before} calling this function.
7242
7243 \sa toLower(), QLocale::toLower()
7244*/
7245
7246QString QString::toUpper_helper(const QString &str)
7247{
7248 return QUnicodeTables::convertCase(str, QUnicodeTables::UpperCase);
7249}
7250
7251QString QString::toUpper_helper(QString &str)
7252{
7253 return QUnicodeTables::convertCase(str, QUnicodeTables::UpperCase);
7254}
7255
7256/*!
7257 \since 5.5
7258
7259 Safely builds a formatted string from the format string \a cformat
7260 and an arbitrary list of arguments.
7261
7262 The format string supports the conversion specifiers, length modifiers,
7263 and flags provided by printf() in the standard C++ library. The \a cformat
7264 string and \c{%s} arguments must be UTF-8 encoded.
7265
7266 \note The \c{%lc} escape sequence expects a unicode character of type
7267 \c char16_t (as returned by QChar::unicode()), or \c ushort.
7268 The \c{%ls} escape sequence expects a pointer to a zero-terminated array
7269 of unicode characters of type \c char16_t, or \c ushort (as returned by
7270 QString::utf16()). This is at odds with the printf() in the standard C++
7271 library, which defines \c {%lc} to print a wchar_t and \c{%ls} to print
7272 a \c{wchar_t*}, and might also produce compiler warnings on platforms
7273 where the size of \c {wchar_t} is not 16 bits.
7274
7275 \warning We do not recommend using QString::asprintf() in new Qt
7276 code. Instead, consider using QTextStream or arg(), both of
7277 which support Unicode strings seamlessly and are type-safe.
7278 Here is an example that uses QTextStream:
7279
7280 \snippet qstring/main.cpp 64
7281
7282 For \l {QObject::tr()}{translations}, especially if the strings
7283 contains more than one escape sequence, you should consider using
7284 the arg() function instead. This allows the order of the
7285 replacements to be controlled by the translator.
7286
7287 \sa arg()
7288*/
7289
7290QString QString::asprintf(const char *cformat, ...)
7291{
7292 va_list ap;
7293 va_start(ap, cformat);
7294 QString s = vasprintf(cformat, ap);
7295 va_end(ap);
7296 return s;
7297}
7298
7299static void append_utf8(QString &qs, const char *cs, qsizetype len)
7300{
7301 const qsizetype oldSize = qs.size();
7302 qs.resize(oldSize + len);
7303 const QChar *newEnd = QUtf8::convertToUnicode(qs.data() + oldSize, QByteArrayView(cs, len));
7304 qs.resize(newEnd - qs.constData());
7305}
7306
7307static uint parse_flag_characters(const char * &c) noexcept
7308{
7309 uint flags = QLocaleData::ZeroPadExponent;
7310 while (true) {
7311 switch (*c) {
7312 case '#':
7315 break;
7316 case '0': flags |= QLocaleData::ZeroPadded; break;
7317 case '-': flags |= QLocaleData::LeftAdjusted; break;
7318 case ' ': flags |= QLocaleData::BlankBeforePositive; break;
7319 case '+': flags |= QLocaleData::AlwaysShowSign; break;
7320 case '\'': flags |= QLocaleData::GroupDigits; break;
7321 default: return flags;
7322 }
7323 ++c;
7324 }
7325}
7326
7327static int parse_field_width(const char *&c, qsizetype size)
7328{
7329 Q_ASSERT(isAsciiDigit(*c));
7330 const char *const stop = c + size;
7331
7332 // can't be negative - started with a digit
7333 // contains at least one digit
7334 auto [result, used] = qstrntoull(c, size, 10);
7335 c += used;
7336 if (used <= 0)
7337 return false;
7338 // preserve Qt 5.5 behavior of consuming all digits, no matter how many
7339 while (c < stop && isAsciiDigit(*c))
7340 ++c;
7341 return result < qulonglong(std::numeric_limits<int>::max()) ? int(result) : 0;
7342}
7343
7345
7346static inline bool can_consume(const char * &c, char ch) noexcept
7347{
7348 if (*c == ch) {
7349 ++c;
7350 return true;
7351 }
7352 return false;
7353}
7354
7355static LengthMod parse_length_modifier(const char * &c) noexcept
7356{
7357 switch (*c++) {
7358 case 'h': return can_consume(c, 'h') ? lm_hh : lm_h;
7359 case 'l': return can_consume(c, 'l') ? lm_ll : lm_l;
7360 case 'L': return lm_L;
7361 case 'j': return lm_j;
7362 case 'z':
7363 case 'Z': return lm_z;
7364 case 't': return lm_t;
7365 }
7366 --c; // don't consume *c - it wasn't a flag
7367 return lm_none;
7368}
7369
7370/*!
7371 \fn QString QString::vasprintf(const char *cformat, va_list ap)
7372 \since 5.5
7373
7374 Equivalent method to asprintf(), but takes a va_list \a ap
7375 instead a list of variable arguments. See the asprintf()
7376 documentation for an explanation of \a cformat.
7377
7378 This method does not call the va_end macro, the caller
7379 is responsible to call va_end on \a ap.
7380
7381 \sa asprintf()
7382*/
7383
7384QString QString::vasprintf(const char *cformat, va_list ap)
7385{
7386 if (!cformat || !*cformat) {
7387 // Qt 1.x compat
7388 return fromLatin1("");
7389 }
7390
7391 // Parse cformat
7392
7393 QString result;
7394 const char *c = cformat;
7395 const char *formatEnd = cformat + qstrlen(cformat);
7396 for (;;) {
7397 // Copy non-escape chars to result
7398 const char *cb = c;
7399 while (*c != '\0' && *c != '%')
7400 c++;
7401 append_utf8(result, cb, qsizetype(c - cb));
7402
7403 if (*c == '\0')
7404 break;
7405
7406 // Found '%'
7407 const char *escape_start = c;
7408 ++c;
7409
7410 if (*c == '\0') {
7411 result.append(u'%'); // a % at the end of the string - treat as non-escape text
7412 break;
7413 }
7414 if (*c == '%') {
7415 result.append(u'%'); // %%
7416 ++c;
7417 continue;
7418 }
7419
7420 uint flags = parse_flag_characters(c);
7421
7422 if (*c == '\0') {
7423 result.append(QLatin1StringView(escape_start)); // incomplete escape, treat as non-escape text
7424 break;
7425 }
7426
7427 // Parse field width
7428 int width = -1; // -1 means unspecified
7429 if (isAsciiDigit(*c)) {
7430 width = parse_field_width(c, formatEnd - c);
7431 } else if (*c == '*') { // can't parse this in another function, not portably, at least
7432 width = va_arg(ap, int);
7433 if (width < 0)
7434 width = -1; // treat all negative numbers as unspecified
7435 ++c;
7436 }
7437
7438 if (*c == '\0') {
7439 result.append(QLatin1StringView(escape_start)); // incomplete escape, treat as non-escape text
7440 break;
7441 }
7442
7443 // Parse precision
7444 int precision = -1; // -1 means unspecified
7445 if (*c == '.') {
7446 ++c;
7447 precision = 0;
7448 if (isAsciiDigit(*c)) {
7449 precision = parse_field_width(c, formatEnd - c);
7450 } else if (*c == '*') { // can't parse this in another function, not portably, at least
7451 precision = va_arg(ap, int);
7452 if (precision < 0)
7453 precision = -1; // treat all negative numbers as unspecified
7454 ++c;
7455 }
7456 }
7457
7458 if (*c == '\0') {
7459 result.append(QLatin1StringView(escape_start)); // incomplete escape, treat as non-escape text
7460 break;
7461 }
7462
7463 const LengthMod length_mod = parse_length_modifier(c);
7464
7465 if (*c == '\0') {
7466 result.append(QLatin1StringView(escape_start)); // incomplete escape, treat as non-escape text
7467 break;
7468 }
7469
7470 // Parse the conversion specifier and do the conversion
7471 QString subst;
7472 switch (*c) {
7473 case 'd':
7474 case 'i': {
7475 qint64 i;
7476 switch (length_mod) {
7477 case lm_none: i = va_arg(ap, int); break;
7478 case lm_hh: i = va_arg(ap, int); break;
7479 case lm_h: i = va_arg(ap, int); break;
7480 case lm_l: i = va_arg(ap, long int); break;
7481 case lm_ll: i = va_arg(ap, qint64); break;
7482 case lm_j: i = qint64{va_arg(ap, intmax_t)}; break;
7483
7484 /* ptrdiff_t actually, but it should be the same for us */
7485 case lm_z: i = va_arg(ap, qsizetype); break;
7486 case lm_t: i = va_arg(ap, qsizetype); break;
7487 default: i = 0; break;
7488 }
7489 subst = QLocaleData::c()->longLongToString(i, precision, 10, width, flags);
7490 ++c;
7491 break;
7492 }
7493 case 'o':
7494 case 'u':
7495 case 'x':
7496 case 'X': {
7497 quint64 u;
7498 switch (length_mod) {
7499 case lm_none: u = va_arg(ap, uint); break;
7500 case lm_hh: u = va_arg(ap, uint); break;
7501 case lm_h: u = va_arg(ap, uint); break;
7502 case lm_l: u = va_arg(ap, ulong); break;
7503 case lm_ll: u = va_arg(ap, quint64); break;
7504 case lm_j: u = quint64{va_arg(ap, uintmax_t)}; break;
7505 case lm_t: u = va_arg(ap, size_t); break;
7506 case lm_z: u = va_arg(ap, size_t); break;
7507 default: u = 0; break;
7508 }
7509
7510 if (isAsciiUpper(*c))
7511 flags |= QLocaleData::CapitalEorX;
7512
7513 int base = 10;
7514 switch (QtMiscUtils::toAsciiLower(*c)) {
7515 case 'o':
7516 base = 8; break;
7517 case 'u':
7518 base = 10; break;
7519 case 'x':
7520 base = 16; break;
7521 default: break;
7522 }
7523 subst = QLocaleData::c()->unsLongLongToString(u, precision, base, width, flags);
7524 ++c;
7525 break;
7526 }
7527 case 'E':
7528 case 'e':
7529 case 'F':
7530 case 'f':
7531 case 'G':
7532 case 'g':
7533 case 'A':
7534 case 'a': {
7535 double d;
7536 if (length_mod == lm_L)
7537 d = va_arg(ap, long double); // not supported - converted to a double
7538 else
7539 d = va_arg(ap, double);
7540
7541 if (isAsciiUpper(*c))
7542 flags |= QLocaleData::CapitalEorX;
7543
7544 QLocaleData::DoubleForm form = QLocaleData::DFDecimal;
7545 switch (QtMiscUtils::toAsciiLower(*c)) {
7546 case 'e': form = QLocaleData::DFExponent; break;
7547 case 'a': // not supported - decimal form used instead
7548 case 'f': form = QLocaleData::DFDecimal; break;
7549 case 'g': form = QLocaleData::DFSignificantDigits; break;
7550 default: break;
7551 }
7552 subst = QLocaleData::c()->doubleToString(d, precision, form, width, flags);
7553 ++c;
7554 break;
7555 }
7556 case 'c': {
7557 if (length_mod == lm_l)
7558 subst = QChar::fromUcs2(va_arg(ap, int));
7559 else
7560 subst = QLatin1Char((uchar) va_arg(ap, int));
7561 ++c;
7562 break;
7563 }
7564 case 's': {
7565 if (length_mod == lm_l) {
7566 const char16_t *buff = va_arg(ap, const char16_t*);
7567 const auto *ch = buff;
7568 while (precision != 0 && *ch != 0) {
7569 ++ch;
7570 --precision;
7571 }
7572 subst.setUtf16(buff, ch - buff);
7573 } else if (precision == -1) {
7574 subst = QString::fromUtf8(va_arg(ap, const char*));
7575 } else {
7576 const char *buff = va_arg(ap, const char*);
7577 subst = QString::fromUtf8(buff, qstrnlen(buff, precision));
7578 }
7579 ++c;
7580 break;
7581 }
7582 case 'p': {
7583 void *arg = va_arg(ap, void*);
7584 const quint64 i = reinterpret_cast<quintptr>(arg);
7585 flags |= QLocaleData::ShowBase;
7586 subst = QLocaleData::c()->unsLongLongToString(i, precision, 16, width, flags);
7587 ++c;
7588 break;
7589 }
7590 case 'n':
7591 switch (length_mod) {
7592 case lm_hh: {
7593 signed char *n = va_arg(ap, signed char*);
7594 *n = result.size();
7595 break;
7596 }
7597 case lm_h: {
7598 short int *n = va_arg(ap, short int*);
7599 *n = result.size();
7600 break;
7601 }
7602 case lm_l: {
7603 long int *n = va_arg(ap, long int*);
7604 *n = result.size();
7605 break;
7606 }
7607 case lm_ll: {
7608 qint64 *n = va_arg(ap, qint64*);
7609 *n = result.size();
7610 break;
7611 }
7612 default: {
7613 int *n = va_arg(ap, int*);
7614 *n = int(result.size());
7615 break;
7616 }
7617 }
7618 ++c;
7619 break;
7620
7621 default: // bad escape, treat as non-escape text
7622 for (const char *cc = escape_start; cc != c; ++cc)
7623 result.append(QLatin1Char(*cc));
7624 continue;
7625 }
7626
7627 if (flags & QLocaleData::LeftAdjusted)
7628 result.append(subst.leftJustified(width));
7629 else
7630 result.append(subst.rightJustified(width));
7631 }
7632
7633 return result;
7634}
7635
7636/*!
7637 \fn QString::toLongLong(bool *ok, int base) const
7638
7639 Returns the string converted to a \c{long long} using base \a
7640 base, which is 10 by default and must be between 2 and 36, or 0.
7641 Returns 0 if the conversion fails.
7642
7643 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
7644 to \c false, and success by setting *\a{ok} to \c true.
7645
7646 If \a base is 0, the C language convention is used: if the string begins
7647 with "0x", base 16 is used; otherwise, if the string begins with "0b", base
7648 2 is used; otherwise, if the string begins with "0", base 8 is used;
7649 otherwise, base 10 is used.
7650
7651 The string conversion will always happen in the 'C' locale. For
7652 locale-dependent conversion use QLocale::toLongLong()
7653
7654 Example:
7655
7656 \snippet qstring/main.cpp 74
7657
7658 This function ignores leading and trailing whitespace.
7659
7660 \note Support for the "0b" prefix was added in Qt 6.4.
7661
7662 \sa number(), toULongLong(), toInt(), QLocale::toLongLong()
7663*/
7664
7665template <typename Int>
7666static Int toIntegral(QStringView string, bool *ok, int base)
7667{
7668#if defined(QT_CHECK_RANGE)
7669 if (base != 0 && (base < 2 || base > 36)) {
7670 qWarning("QString::toIntegral: Invalid base (%d)", base);
7671 base = 10;
7672 }
7673#endif
7674
7675 QVarLengthArray<uchar> latin1(string.size());
7676 qt_to_latin1(latin1.data(), string.utf16(), string.size());
7677 QSimpleParsedNumber<Int> r;
7678 if constexpr (std::is_signed_v<Int>)
7679 r = QLocaleData::bytearrayToLongLong(latin1, base);
7680 else
7681 r = QLocaleData::bytearrayToUnsLongLong(latin1, base);
7682 if (ok)
7683 *ok = r.ok();
7684 return r.result;
7685}
7686
7687qlonglong QString::toIntegral_helper(QStringView string, bool *ok, int base)
7688{
7689 return toIntegral<qlonglong>(string, ok, base);
7690}
7691
7692/*!
7693 \fn QString::toULongLong(bool *ok, int base) const
7694
7695 Returns the string converted to an \c{unsigned long long} using base \a
7696 base, which is 10 by default and must be between 2 and 36, or 0.
7697 Returns 0 if the conversion fails.
7698
7699 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
7700 to \c false, and success by setting *\a{ok} to \c true.
7701
7702 If \a base is 0, the C language convention is used: if the string begins
7703 with "0x", base 16 is used; otherwise, if the string begins with "0b", base
7704 2 is used; otherwise, if the string begins with "0", base 8 is used;
7705 otherwise, base 10 is used.
7706
7707 The string conversion will always happen in the 'C' locale. For
7708 locale-dependent conversion use QLocale::toULongLong()
7709
7710 Example:
7711
7712 \snippet qstring/main.cpp 79
7713
7714 This function ignores leading and trailing whitespace.
7715
7716 \note Support for the "0b" prefix was added in Qt 6.4.
7717
7718 \sa number(), toLongLong(), QLocale::toULongLong()
7719*/
7720
7721qulonglong QString::toIntegral_helper(QStringView string, bool *ok, uint base)
7722{
7723 return toIntegral<qulonglong>(string, ok, base);
7724}
7725
7726/*!
7727 \fn long QString::toLong(bool *ok, int base) const
7728
7729 Returns the string converted to a \c long using base \a
7730 base, which is 10 by default and must be between 2 and 36, or 0.
7731 Returns 0 if the conversion fails.
7732
7733 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
7734 to \c false, and success by setting *\a{ok} to \c true.
7735
7736 If \a base is 0, the C language convention is used: if the string begins
7737 with "0x", base 16 is used; otherwise, if the string begins with "0b", base
7738 2 is used; otherwise, if the string begins with "0", base 8 is used;
7739 otherwise, base 10 is used.
7740
7741 The string conversion will always happen in the 'C' locale. For
7742 locale-dependent conversion use QLocale::toLongLong()
7743
7744 Example:
7745
7746 \snippet qstring/main.cpp 73
7747
7748 This function ignores leading and trailing whitespace.
7749
7750 \note Support for the "0b" prefix was added in Qt 6.4.
7751
7752 \sa number(), toULong(), toInt(), QLocale::toInt()
7753*/
7754
7755/*!
7756 \fn ulong QString::toULong(bool *ok, int base) const
7757
7758 Returns the string converted to an \c{unsigned long} using base \a
7759 base, which is 10 by default and must be between 2 and 36, or 0.
7760 Returns 0 if the conversion fails.
7761
7762 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
7763 to \c false, and success by setting *\a{ok} to \c true.
7764
7765 If \a base is 0, the C language convention is used: if the string begins
7766 with "0x", base 16 is used; otherwise, if the string begins with "0b", base
7767 2 is used; otherwise, if the string begins with "0", base 8 is used;
7768 otherwise, base 10 is used.
7769
7770 The string conversion will always happen in the 'C' locale. For
7771 locale-dependent conversion use QLocale::toULongLong()
7772
7773 Example:
7774
7775 \snippet qstring/main.cpp 78
7776
7777 This function ignores leading and trailing whitespace.
7778
7779 \note Support for the "0b" prefix was added in Qt 6.4.
7780
7781 \sa number(), QLocale::toUInt()
7782*/
7783
7784/*!
7785 \fn int QString::toInt(bool *ok, int base) const
7786 Returns the string converted to an \c int using base \a
7787 base, which is 10 by default and must be between 2 and 36, or 0.
7788 Returns 0 if the conversion fails.
7789
7790 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
7791 to \c false, and success by setting *\a{ok} to \c true.
7792
7793 If \a base is 0, the C language convention is used: if the string begins
7794 with "0x", base 16 is used; otherwise, if the string begins with "0b", base
7795 2 is used; otherwise, if the string begins with "0", base 8 is used;
7796 otherwise, base 10 is used.
7797
7798 The string conversion will always happen in the 'C' locale. For
7799 locale-dependent conversion use QLocale::toInt()
7800
7801 Example:
7802
7803 \snippet qstring/main.cpp 72
7804
7805 This function ignores leading and trailing whitespace.
7806
7807 \note Support for the "0b" prefix was added in Qt 6.4.
7808
7809 \sa number(), toUInt(), toDouble(), QLocale::toInt()
7810*/
7811
7812/*!
7813 \fn uint QString::toUInt(bool *ok, int base) const
7814 Returns the string converted to an \c{unsigned int} using base \a
7815 base, which is 10 by default and must be between 2 and 36, or 0.
7816 Returns 0 if the conversion fails.
7817
7818 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
7819 to \c false, and success by setting *\a{ok} to \c true.
7820
7821 If \a base is 0, the C language convention is used: if the string begins
7822 with "0x", base 16 is used; otherwise, if the string begins with "0b", base
7823 2 is used; otherwise, if the string begins with "0", base 8 is used;
7824 otherwise, base 10 is used.
7825
7826 The string conversion will always happen in the 'C' locale. For
7827 locale-dependent conversion use QLocale::toUInt()
7828
7829 Example:
7830
7831 \snippet qstring/main.cpp 77
7832
7833 This function ignores leading and trailing whitespace.
7834
7835 \note Support for the "0b" prefix was added in Qt 6.4.
7836
7837 \sa number(), toInt(), QLocale::toUInt()
7838*/
7839
7840/*!
7841 \fn short QString::toShort(bool *ok, int base) const
7842
7843 Returns the string converted to a \c short using base \a
7844 base, which is 10 by default and must be between 2 and 36, or 0.
7845 Returns 0 if the conversion fails.
7846
7847 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
7848 to \c false, and success by setting *\a{ok} to \c true.
7849
7850 If \a base is 0, the C language convention is used: if the string begins
7851 with "0x", base 16 is used; otherwise, if the string begins with "0b", base
7852 2 is used; otherwise, if the string begins with "0", base 8 is used;
7853 otherwise, base 10 is used.
7854
7855 The string conversion will always happen in the 'C' locale. For
7856 locale-dependent conversion use QLocale::toShort()
7857
7858 Example:
7859
7860 \snippet qstring/main.cpp 76
7861
7862 This function ignores leading and trailing whitespace.
7863
7864 \note Support for the "0b" prefix was added in Qt 6.4.
7865
7866 \sa number(), toUShort(), toInt(), QLocale::toShort()
7867*/
7868
7869/*!
7870 \fn ushort QString::toUShort(bool *ok, int base) const
7871
7872 Returns the string converted to an \c{unsigned short} using base \a
7873 base, which is 10 by default and must be between 2 and 36, or 0.
7874 Returns 0 if the conversion fails.
7875
7876 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
7877 to \c false, and success by setting *\a{ok} to \c true.
7878
7879 If \a base is 0, the C language convention is used: if the string begins
7880 with "0x", base 16 is used; otherwise, if the string begins with "0b", base
7881 2 is used; otherwise, if the string begins with "0", base 8 is used;
7882 otherwise, base 10 is used.
7883
7884 The string conversion will always happen in the 'C' locale. For
7885 locale-dependent conversion use QLocale::toUShort()
7886
7887 Example:
7888
7889 \snippet qstring/main.cpp 80
7890
7891 This function ignores leading and trailing whitespace.
7892
7893 \note Support for the "0b" prefix was added in Qt 6.4.
7894
7895 \sa number(), toShort(), QLocale::toUShort()
7896*/
7897
7898/*!
7899 Returns the string converted to a \c double value.
7900
7901 Returns an infinity if the conversion overflows or 0.0 if the
7902 conversion fails for other reasons (e.g. underflow).
7903
7904 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
7905 to \c false, and success by setting *\a{ok} to \c true.
7906
7907 \snippet qstring/main.cpp 66
7908
7909 \warning The QString content may only contain valid numerical characters
7910 which includes the plus/minus sign, the character e used in scientific
7911 notation, and the decimal point. Including the unit or additional characters
7912 leads to a conversion error.
7913
7914 \snippet qstring/main.cpp 67
7915
7916 The string conversion will always happen in the 'C' locale. For
7917 locale-dependent conversion use QLocale::toDouble()
7918
7919 \snippet qstring/main.cpp 68
7920
7921 For historical reasons, this function does not handle
7922 thousands group separators. If you need to convert such numbers,
7923 use QLocale::toDouble().
7924
7925 \snippet qstring/main.cpp 69
7926
7927 This function ignores leading and trailing whitespace.
7928
7929 \sa number(), QLocale::setDefault(), QLocale::toDouble(), trimmed()
7930*/
7931
7932double QString::toDouble(bool *ok) const
7933{
7934 return QStringView(*this).toDouble(ok);
7935}
7936
7937double QStringView::toDouble(bool *ok) const
7938{
7939 QStringView string = qt_trimmed(*this);
7940 QVarLengthArray<uchar> latin1(string.size());
7941 qt_to_latin1(latin1.data(), string.utf16(), string.size());
7942 auto r = qt_asciiToDouble(reinterpret_cast<const char *>(latin1.data()), string.size());
7943 if (ok != nullptr)
7944 *ok = r.ok();
7945 return r.result;
7946}
7947
7948/*!
7949 Returns the string converted to a \c float value.
7950
7951 Returns an infinity if the conversion overflows or 0.0 if the
7952 conversion fails for other reasons (e.g. underflow).
7953
7954 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
7955 to \c false, and success by setting *\a{ok} to \c true.
7956
7957 \warning The QString content may only contain valid numerical characters
7958 which includes the plus/minus sign, the character e used in scientific
7959 notation, and the decimal point. Including the unit or additional characters
7960 leads to a conversion error.
7961
7962 The string conversion will always happen in the 'C' locale. For
7963 locale-dependent conversion use QLocale::toFloat()
7964
7965 For historical reasons, this function does not handle
7966 thousands group separators. If you need to convert such numbers,
7967 use QLocale::toFloat().
7968
7969 Example:
7970
7971 \snippet qstring/main.cpp 71
7972
7973 This function ignores leading and trailing whitespace.
7974
7975 \sa number(), toDouble(), toInt(), QLocale::toFloat(), trimmed()
7976*/
7977
7978float QString::toFloat(bool *ok) const
7979{
7980 return QLocaleData::convertDoubleToFloat(toDouble(ok), ok);
7981}
7982
7983float QStringView::toFloat(bool *ok) const
7984{
7985 return QLocaleData::convertDoubleToFloat(toDouble(ok), ok);
7986}
7987
7988/*! \fn QString &QString::setNum(int n, int base)
7989
7990 Sets the string to the printed value of \a n in the specified \a
7991 base, and returns a reference to the string.
7992
7993 The base is 10 by default and must be between 2 and 36.
7994
7995 \snippet qstring/main.cpp 56
7996
7997 The formatting always uses QLocale::C, i.e., English/UnitedStates.
7998 To get a localized string representation of a number, use
7999 QLocale::toString() with the appropriate locale.
8000
8001 \sa number()
8002*/
8003
8004/*! \fn QString &QString::setNum(uint n, int base)
8005
8006 \overload
8007*/
8008
8009/*! \fn QString &QString::setNum(long n, int base)
8010
8011 \overload
8012*/
8013
8014/*! \fn QString &QString::setNum(ulong n, int base)
8015
8016 \overload
8017*/
8018
8019/*!
8020 \overload
8021*/
8022QString &QString::setNum(qlonglong n, int base)
8023{
8024 return *this = number(n, base);
8025}
8026
8027/*!
8028 \overload
8029*/
8030QString &QString::setNum(qulonglong n, int base)
8031{
8032 return *this = number(n, base);
8033}
8034
8035/*! \fn QString &QString::setNum(short n, int base)
8036
8037 \overload
8038*/
8039
8040/*! \fn QString &QString::setNum(ushort n, int base)
8041
8042 \overload
8043*/
8044
8045/*!
8046 \overload
8047
8048 Sets the string to the printed value of \a n, formatted according to the
8049 given \a format and \a precision, and returns a reference to the string.
8050
8051 \sa number(), QLocale::FloatingPointPrecisionOption, {Number formats}
8052*/
8053
8054QString &QString::setNum(double n, char format, int precision)
8055{
8056 return *this = number(n, format, precision);
8057}
8058
8059/*!
8060 \fn QString &QString::setNum(float n, char format, int precision)
8061 \overload
8062
8063 Sets the string to the printed value of \a n, formatted according
8064 to the given \a format and \a precision, and returns a reference
8065 to the string.
8066
8067 The formatting always uses QLocale::C, i.e., English/UnitedStates.
8068 To get a localized string representation of a number, use
8069 QLocale::toString() with the appropriate locale.
8070
8071 \sa number()
8072*/
8073
8074
8075/*!
8076 \fn QString QString::number(long n, int base)
8077
8078 Returns a string equivalent of the number \a n according to the
8079 specified \a base.
8080
8081 The base is 10 by default and must be between 2
8082 and 36. For bases other than 10, \a n is treated as an
8083 unsigned integer.
8084
8085 The formatting always uses QLocale::C, i.e., English/UnitedStates.
8086 To get a localized string representation of a number, use
8087 QLocale::toString() with the appropriate locale.
8088
8089 \snippet qstring/main.cpp 35
8090
8091 \sa setNum()
8092*/
8093
8094QString QString::number(long n, int base)
8095{
8096 return number(qlonglong(n), base);
8097}
8098
8099/*!
8100 \fn QString QString::number(ulong n, int base)
8101
8102 \overload
8103*/
8104QString QString::number(ulong n, int base)
8105{
8106 return number(qulonglong(n), base);
8107}
8108
8109/*!
8110 \overload
8111*/
8112QString QString::number(int n, int base)
8113{
8114 return number(qlonglong(n), base);
8115}
8116
8117/*!
8118 \overload
8119*/
8120QString QString::number(uint n, int base)
8121{
8122 return number(qulonglong(n), base);
8123}
8124
8125/*!
8126 \overload
8127*/
8128QString QString::number(qlonglong n, int base)
8129{
8130#if defined(QT_CHECK_RANGE)
8131 if (base < 2 || base > 36) {
8132 qWarning("QString::setNum: Invalid base (%d)", base);
8133 base = 10;
8134 }
8135#endif
8136 bool negative = n < 0;
8137 /*
8138 Negating std::numeric_limits<qlonglong>::min() hits undefined behavior, so
8139 taking an absolute value has to take a slight detour.
8140 */
8141 return qulltoBasicLatin(negative ? 1u + qulonglong(-(n + 1)) : qulonglong(n), base, negative);
8142}
8143
8144/*!
8145 \overload
8146*/
8147QString QString::number(qulonglong n, int base)
8148{
8149#if defined(QT_CHECK_RANGE)
8150 if (base < 2 || base > 36) {
8151 qWarning("QString::setNum: Invalid base (%d)", base);
8152 base = 10;
8153 }
8154#endif
8155 return qulltoBasicLatin(n, base, false);
8156}
8157
8158
8159/*!
8160 Returns a string representing the floating-point number \a n.
8161
8162 Returns a string that represents \a n, formatted according to the specified
8163 \a format and \a precision.
8164
8165 For formats with an exponent, the exponent will show its sign and have at
8166 least two digits, left-padding the exponent with zero if needed.
8167
8168 \sa setNum(), QLocale::toString(), QLocale::FloatingPointPrecisionOption, {Number formats}
8169*/
8170QString QString::number(double n, char format, int precision)
8171{
8172 QLocaleData::DoubleForm form = QLocaleData::DFDecimal;
8173
8174 switch (QtMiscUtils::toAsciiLower(format)) {
8175 case 'f':
8176 form = QLocaleData::DFDecimal;
8177 break;
8178 case 'e':
8179 form = QLocaleData::DFExponent;
8180 break;
8181 case 'g':
8182 form = QLocaleData::DFSignificantDigits;
8183 break;
8184 default:
8185#if defined(QT_CHECK_RANGE)
8186 qWarning("QString::setNum: Invalid format char '%c'", format);
8187#endif
8188 break;
8189 }
8190
8191 return qdtoBasicLatin(n, form, precision, isAsciiUpper(format));
8192}
8193
8194namespace {
8195template<class ResultList, class StringSource>
8196static ResultList splitString(const StringSource &source, QStringView sep,
8197 Qt::SplitBehavior behavior, Qt::CaseSensitivity cs)
8198{
8199 ResultList list;
8200 typename StringSource::size_type start = 0;
8201 typename StringSource::size_type end;
8202 typename StringSource::size_type extra = 0;
8203 while ((end = QtPrivate::findString(QStringView(source.constData(), source.size()), start + extra, sep, cs)) != -1) {
8204 if (start != end || behavior == Qt::KeepEmptyParts)
8205 list.append(source.sliced(start, end - start));
8206 start = end + sep.size();
8207 extra = (sep.size() == 0 ? 1 : 0);
8208 }
8209 if (start != source.size() || behavior == Qt::KeepEmptyParts)
8210 list.append(source.sliced(start));
8211 return list;
8212}
8213
8214} // namespace
8215
8216/*!
8217 Splits the string into substrings wherever \a sep occurs, and
8218 returns the list of those strings. If \a sep does not match
8219 anywhere in the string, split() returns a single-element list
8220 containing this string.
8221
8222 \a cs specifies whether \a sep should be matched case
8223 sensitively or case insensitively.
8224
8225 If \a behavior is Qt::SkipEmptyParts, empty entries don't
8226 appear in the result. By default, empty entries are kept.
8227
8228 Example:
8229
8230 \snippet qstring/main.cpp 62
8231
8232 If \a sep is empty, split() returns an empty string, followed
8233 by each of the string's characters, followed by another empty string:
8234
8235 \snippet qstring/main.cpp 62-empty
8236
8237 To understand this behavior, recall that the empty string matches
8238 everywhere, so the above is qualitatively the same as:
8239
8240 \snippet qstring/main.cpp 62-slashes
8241
8242 \sa QStringList::join(), section()
8243
8244 \since 5.14
8245*/
8246QStringList QString::split(const QString &sep, Qt::SplitBehavior behavior, Qt::CaseSensitivity cs) const
8247{
8248 return splitString<QStringList>(*this, sep, behavior, cs);
8249}
8250
8251/*!
8252 \overload
8253 \since 5.14
8254*/
8255QStringList QString::split(QChar sep, Qt::SplitBehavior behavior, Qt::CaseSensitivity cs) const
8256{
8257 return splitString<QStringList>(*this, QStringView(&sep, 1), behavior, cs);
8258}
8259
8260/*!
8261 \fn QList<QStringView> QStringView::split(QChar sep, Qt::SplitBehavior behavior, Qt::CaseSensitivity cs) const
8262 \fn QList<QStringView> QStringView::split(QStringView sep, Qt::SplitBehavior behavior, Qt::CaseSensitivity cs) const
8263
8264
8265 Splits the view into substring views wherever \a sep occurs, and
8266 returns the list of those string views.
8267
8268 See QString::split() for how \a sep, \a behavior and \a cs interact to form
8269 the result.
8270
8271 \note All the returned views are valid as long as the data referenced by
8272 this string view is valid. Destroying the data will cause all views to
8273 become dangling.
8274
8275 \since 6.0
8276*/
8277QList<QStringView> QStringView::split(QStringView sep, Qt::SplitBehavior behavior, Qt::CaseSensitivity cs) const
8278{
8279 return splitString<QList<QStringView>>(QStringView(*this), sep, behavior, cs);
8280}
8281
8282QList<QStringView> QStringView::split(QChar sep, Qt::SplitBehavior behavior, Qt::CaseSensitivity cs) const
8283{
8284 return split(QStringView(&sep, 1), behavior, cs);
8285}
8286
8287#if QT_CONFIG(regularexpression)
8288namespace {
8289template<class ResultList, typename String, typename MatchingFunction>
8290static ResultList splitString(const String &source, const QRegularExpression &re,
8291 MatchingFunction matchingFunction,
8292 Qt::SplitBehavior behavior)
8293{
8294 ResultList list;
8295 if (!re.isValid()) {
8296 qtWarnAboutInvalidRegularExpression(re, "QString", "split");
8297 return list;
8298 }
8299
8300 qsizetype start = 0;
8301 qsizetype end = 0;
8302 QRegularExpressionMatchIterator iterator = (re.*matchingFunction)(source, 0, QRegularExpression::NormalMatch, QRegularExpression::NoMatchOption);
8303 while (iterator.hasNext()) {
8304 QRegularExpressionMatch match = iterator.next();
8305 end = match.capturedStart();
8306 if (start != end || behavior == Qt::KeepEmptyParts)
8307 list.append(source.sliced(start, end - start));
8308 start = match.capturedEnd();
8309 }
8310
8311 if (start != source.size() || behavior == Qt::KeepEmptyParts)
8312 list.append(source.sliced(start));
8313
8314 return list;
8315}
8316} // namespace
8317
8318/*!
8319 \overload
8320 \since 5.14
8321
8322 Splits the string into substrings wherever the regular expression
8323 \a re matches, and returns the list of those strings. If \a re
8324 does not match anywhere in the string, split() returns a
8325 single-element list containing this string.
8326
8327 Here is an example where we extract the words in a sentence
8328 using one or more whitespace characters as the separator:
8329
8330 \snippet qstring/main.cpp 90
8331
8332 Here is a similar example, but this time we use any sequence of
8333 non-word characters as the separator:
8334
8335 \snippet qstring/main.cpp 91
8336
8337 Here is a third example where we use a zero-length assertion,
8338 \b{\\b} (word boundary), to split the string into an
8339 alternating sequence of non-word and word tokens:
8340
8341 \snippet qstring/main.cpp 92
8342
8343 \sa QStringList::join(), section()
8344*/
8345QStringList QString::split(const QRegularExpression &re, Qt::SplitBehavior behavior) const
8346{
8347#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0)
8348 const auto matchingFunction = qOverload<const QString &, qsizetype, QRegularExpression::MatchType, QRegularExpression::MatchOptions>(&QRegularExpression::globalMatch);
8349#else
8350 const auto matchingFunction = &QRegularExpression::globalMatch;
8351#endif
8352 return splitString<QStringList>(*this,
8353 re,
8354 matchingFunction,
8355 behavior);
8356}
8357
8358/*!
8359 \overload
8360 \since 6.0
8361
8362 Splits the string into substring views wherever the regular expression \a re
8363 matches, and returns the list of those strings. If \a re does not match
8364 anywhere in the string, split() returns a single-element list containing
8365 this string as view.
8366
8367 \note The views in the returned list are sub-views of this view; as such,
8368 they reference the same data as it and only remain valid for as long as that
8369 data remains live.
8370*/
8371QList<QStringView> QStringView::split(const QRegularExpression &re, Qt::SplitBehavior behavior) const
8372{
8373 return splitString<QList<QStringView>>(*this, re, &QRegularExpression::globalMatchView, behavior);
8374}
8375
8376#endif // QT_CONFIG(regularexpression)
8377
8378/*!
8379 \enum QString::NormalizationForm
8380
8381 This enum describes the various normalized forms of Unicode text.
8382
8383 \value NormalizationForm_D Canonical Decomposition
8384 \value NormalizationForm_C Canonical Decomposition followed by Canonical Composition
8385 \value NormalizationForm_KD Compatibility Decomposition
8386 \value NormalizationForm_KC Compatibility Decomposition followed by Canonical Composition
8387
8388 \sa normalized(),
8389 {https://www.unicode.org/reports/tr15/}{Unicode Standard Annex #15}
8390*/
8391
8392/*!
8393 \since 4.5
8394
8395 Returns a copy of this string repeated the specified number of \a times.
8396
8397 If \a times is less than 1, an empty string is returned.
8398
8399 Example:
8400
8401 \snippet code/src_corelib_text_qstring.cpp 8
8402*/
8403QString QString::repeated(qsizetype times) const
8404{
8405 if (d.size == 0)
8406 return *this;
8407
8408 if (times <= 1) {
8409 if (times == 1)
8410 return *this;
8411 return QString();
8412 }
8413
8414 const qsizetype resultSize = [&] {
8415 auto r = times;
8416 if (mul_overflow(r, d.size, &r))
8417 qBadAlloc();
8418 return r;
8419 }();
8420
8421 QString result;
8422 result.reserve(resultSize);
8423 if (result.capacity() != resultSize)
8424 return QString(); // not enough memory
8425
8426 memcpy(result.d.data(), d.data(), d.size * sizeof(QChar));
8427
8428 qsizetype sizeSoFar = d.size;
8429 char16_t *end = result.d.data() + sizeSoFar;
8430
8431 const qsizetype halfResultSize = resultSize >> 1;
8432 while (sizeSoFar <= halfResultSize) {
8433 memcpy(end, result.d.data(), sizeSoFar * sizeof(QChar));
8434 end += sizeSoFar;
8435 sizeSoFar <<= 1;
8436 }
8437 memcpy(end, result.d.data(), (resultSize - sizeSoFar) * sizeof(QChar));
8438 result.d.data()[resultSize] = '\0';
8439 result.d.size = resultSize;
8440 return result;
8441}
8442
8443void qt_string_normalize(QString *data, QString::NormalizationForm mode, QChar::UnicodeVersion version, qsizetype from)
8444{
8445 {
8446 // check if it's fully ASCII first, because then we have no work
8447 auto start = reinterpret_cast<const char16_t *>(data->constData());
8448 const char16_t *p = start + from;
8449 if (isAscii_helper(p, p + data->size() - from))
8450 return;
8451 if (p > start + from)
8452 from = p - start - 1; // need one before the non-ASCII to perform NFC
8453 }
8454
8455 if (version == QChar::Unicode_Unassigned) {
8456 version = QChar::currentUnicodeVersion();
8457 } else if (int(version) <= NormalizationCorrectionsVersionMax) {
8458 const QString &s = *data;
8459 QChar *d = nullptr;
8461 if (n.version > version) {
8462 qsizetype pos = from;
8463 if (QChar::requiresSurrogates(n.ucs4)) {
8464 char16_t ucs4High = QChar::highSurrogate(n.ucs4);
8465 char16_t ucs4Low = QChar::lowSurrogate(n.ucs4);
8466
8467 // scan for this codepoint
8468 for ( ; pos < s.size() - 1; ++pos) {
8469 if (s.at(pos).unicode() == ucs4High && s.at(pos + 1).unicode() == ucs4Low)
8470 break;
8471 }
8472 if (pos == s.size())
8473 continue; // no correction necessary
8474
8475 // detach if necessary
8476 if (!d)
8477 d = data->data();
8478 if (QChar::requiresSurrogates(n.old_mapping)) {
8479 // no shrinking
8480 char16_t oldHigh = QChar::highSurrogate(n.old_mapping);
8481 char16_t oldLow = QChar::lowSurrogate(n.old_mapping);
8482 while (pos < s.size() - 1) {
8483 if (s.at(pos).unicode() == ucs4High && s.at(pos + 1).unicode() == ucs4Low) {
8484 d[pos] = QChar(oldHigh);
8485 d[++pos] = QChar(oldLow);
8486 }
8487 ++pos;
8488 }
8489 } else {
8490 // shrinking, so a little harder
8491 char16_t old = char16_t(n.old_mapping);
8492 qsizetype outpos = pos;
8493 for ( ; pos < s.size(); ++outpos, ++pos) {
8494 if (pos < s.size() - 1 && s.at(pos).unicode() == ucs4High
8495 && s.at(pos + 1).unicode() == ucs4Low) {
8496 d[outpos] = QChar(old);
8497 ++pos;
8498 }
8499 }
8500 data->truncate(outpos);
8501 d = nullptr;
8502 }
8503 } else {
8504 Q_ASSERT(!QChar::requiresSurrogates(n.old_mapping)); // BMP maps to BMP
8505 while (pos < s.size()) {
8506 if (s.at(pos).unicode() == n.ucs4) {
8507 if (!d)
8508 d = data->data();
8509 d[pos] = QChar(n.old_mapping);
8510 }
8511 ++pos;
8512 }
8513 }
8514 }
8515 }
8516 }
8517
8518 if (normalizationQuickCheckHelper(data, mode, from, &from))
8519 return;
8520
8521 decomposeHelper(data, mode < QString::NormalizationForm_KD, version, from);
8522
8523 canonicalOrderHelper(data, version, from);
8524
8525 if (mode == QString::NormalizationForm_D || mode == QString::NormalizationForm_KD)
8526 return;
8527
8528 composeHelper(data, version, from);
8529}
8530
8531/*!
8532 Returns the string in the given Unicode normalization \a mode,
8533 according to the given \a version of the Unicode standard.
8534*/
8535QString QString::normalized(QString::NormalizationForm mode, QChar::UnicodeVersion version) const
8536{
8537 QString copy = *this;
8538 qt_string_normalize(&copy, mode, version, 0);
8539 return copy;
8540}
8541
8542#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0) && !defined(QT_BOOTSTRAPPED)
8543static void checkArgEscape(QStringView s)
8544{
8545 // If we're in here, it means that qArgDigitValue has accepted the
8546 // digit. We can skip the check in case we already know it will
8547 // succeed.
8548 if (!supportUnicodeDigitValuesInArg())
8549 return;
8550
8551 const auto isNonAsciiDigit = [](QChar c) {
8552 return c.unicode() < u'0' || c.unicode() > u'9';
8553 };
8554
8555 if (std::any_of(s.begin(), s.end(), isNonAsciiDigit)) {
8556 const auto accumulateDigit = [](int partial, QChar digit) {
8557 return partial * 10 + digit.digitValue();
8558 };
8559 const int parsedNumber = std::accumulate(s.begin(), s.end(), 0, accumulateDigit);
8560
8561 qWarning("QString::arg(): the replacement \"%%%ls\" contains non-ASCII digits;\n"
8562 " it is currently being interpreted as the %d-th substitution.\n"
8563 " This is deprecated; support for non-ASCII digits will be dropped\n"
8564 " in a future version of Qt.",
8565 qUtf16Printable(s.toString()),
8566 parsedNumber);
8567 }
8568}
8569#endif
8570
8572{
8573 int min_escape; // lowest escape sequence number
8574 qsizetype occurrences; // number of occurrences of the lowest escape sequence number
8575 qsizetype locale_occurrences; // number of occurrences of the lowest escape sequence number that
8576 // contain 'L'
8577 qsizetype escape_len; // total length of escape sequences which will be replaced
8578};
8579
8580static ArgEscapeData findArgEscapes(QStringView s)
8581{
8582 const QChar *uc_begin = s.begin();
8583 const QChar *uc_end = s.end();
8584
8585 ArgEscapeData d;
8586
8587 d.min_escape = INT_MAX;
8588 d.occurrences = 0;
8589 d.escape_len = 0;
8590 d.locale_occurrences = 0;
8591
8592 const QChar *c = uc_begin;
8593 while (c != uc_end) {
8594 while (c != uc_end && c->unicode() != '%')
8595 ++c;
8596
8597 if (c == uc_end)
8598 break;
8599 const QChar *escape_start = c;
8600 if (++c == uc_end)
8601 break;
8602
8603 bool locale_arg = false;
8604 if (c->unicode() == 'L') {
8605 locale_arg = true;
8606 if (++c == uc_end)
8607 break;
8608 }
8609
8610 int escape = qArgDigitValue(*c);
8611 if (escape == -1)
8612 continue;
8613
8614 // ### Qt 7: do not allow anything but ASCII digits
8615 // in arg()'s replacements.
8616#if QT_VERSION <= QT_VERSION_CHECK(7, 0, 0) && !defined(QT_BOOTSTRAPPED)
8617 const QChar *escapeBegin = c;
8618 const QChar *escapeEnd = escapeBegin + 1;
8619#endif
8620
8621 ++c;
8622
8623 if (c != uc_end) {
8624 const int next_escape = qArgDigitValue(*c);
8625 if (next_escape != -1) {
8626 escape = (10 * escape) + next_escape;
8627 ++c;
8628#if QT_VERSION <= QT_VERSION_CHECK(7, 0, 0) && !defined(QT_BOOTSTRAPPED)
8629 ++escapeEnd;
8630#endif
8631 }
8632 }
8633
8634#if QT_VERSION <= QT_VERSION_CHECK(7, 0, 0) && !defined(QT_BOOTSTRAPPED)
8635 checkArgEscape(QStringView(escapeBegin, escapeEnd));
8636#endif
8637
8638 if (escape > d.min_escape)
8639 continue;
8640
8641 if (escape < d.min_escape) {
8642 d.min_escape = escape;
8643 d.occurrences = 0;
8644 d.escape_len = 0;
8645 d.locale_occurrences = 0;
8646 }
8647
8648 ++d.occurrences;
8649 if (locale_arg)
8650 ++d.locale_occurrences;
8651 d.escape_len += c - escape_start;
8652 }
8653 return d;
8654}
8655
8656static QString replaceArgEscapes(QStringView s, const ArgEscapeData &d, qsizetype field_width,
8657 QStringView arg, QStringView larg, QChar fillChar)
8658{
8659 // Negative field-width for right-padding, positive for left-padding:
8660 const qsizetype abs_field_width = qAbs(field_width);
8661 const qsizetype result_len =
8662 s.size() - d.escape_len
8663 + (d.occurrences - d.locale_occurrences) * qMax(abs_field_width, arg.size())
8664 + d.locale_occurrences * qMax(abs_field_width, larg.size());
8665
8666 QString result(result_len, Qt::Uninitialized);
8667 QChar *rc = const_cast<QChar *>(result.unicode());
8668 QChar *const result_end = rc + result_len;
8669 qsizetype repl_cnt = 0;
8670
8671 const QChar *c = s.begin();
8672 const QChar *const uc_end = s.end();
8673 while (c != uc_end) {
8674 Q_ASSERT(d.occurrences > repl_cnt);
8675 /* We don't have to check increments of c against uc_end because, as
8676 long as d.occurrences > repl_cnt, we KNOW there are valid escape
8677 sequences remaining. */
8678
8679 const QChar *text_start = c;
8680 while (c->unicode() != '%')
8681 ++c;
8682
8683 const QChar *escape_start = c++;
8684 const bool localize = c->unicode() == 'L';
8685 if (localize)
8686 ++c;
8687
8688 int escape = qArgDigitValue(*c);
8689 if (escape != -1 && c + 1 != uc_end) {
8690 const int digit = qArgDigitValue(c[1]);
8691 if (digit != -1) {
8692 ++c;
8693 escape = 10 * escape + digit;
8694 }
8695 }
8696
8697 if (escape != d.min_escape) {
8698 memcpy(rc, text_start, (c - text_start) * sizeof(QChar));
8699 rc += c - text_start;
8700 } else {
8701 ++c;
8702
8703 memcpy(rc, text_start, (escape_start - text_start) * sizeof(QChar));
8704 rc += escape_start - text_start;
8705
8706 const QStringView use = localize ? larg : arg;
8707 const qsizetype pad_chars = abs_field_width - use.size();
8708 // (If negative, relevant loops are no-ops: no need to check.)
8709
8710 if (field_width > 0) { // left padded
8711 rc = std::fill_n(rc, pad_chars, fillChar);
8712 }
8713
8714 if (use.size())
8715 memcpy(rc, use.data(), use.size() * sizeof(QChar));
8716 rc += use.size();
8717
8718 if (field_width < 0) { // right padded
8719 rc = std::fill_n(rc, pad_chars, fillChar);
8720 }
8721
8722 if (++repl_cnt == d.occurrences) {
8723 memcpy(rc, c, (uc_end - c) * sizeof(QChar));
8724 rc += uc_end - c;
8725 Q_ASSERT(rc == result_end);
8726 c = uc_end;
8727 }
8728 }
8729 }
8730 Q_ASSERT(rc == result_end);
8731
8732 return result;
8733}
8734
8735/*!
8736 \fn template <typename T, QString::if_string_like<T> = true> QString QString::arg(const T &a, int fieldWidth, QChar fillChar) const
8737
8738 Returns a copy of this string with the lowest-numbered place-marker
8739 replaced by string \a a, i.e., \c %1, \c %2, ..., \c %99.
8740
8741 \a fieldWidth specifies the minimum amount of space that \a a
8742 shall occupy. If \a a requires less space than \a fieldWidth, it
8743 is padded to \a fieldWidth with character \a fillChar. A positive
8744 \a fieldWidth produces right-aligned text. A negative \a fieldWidth
8745 produces left-aligned text.
8746
8747 This example shows how we might create a \c status string for
8748 reporting progress while processing a list of files:
8749
8750 \snippet qstring/main.cpp 11-qstringview
8751
8752 First, \c arg(i) replaces \c %1. Then \c arg(total) replaces \c
8753 %2. Finally, \c arg(fileName) replaces \c %3.
8754
8755 One advantage of using arg() over asprintf() is that the order of the
8756 numbered place markers can change, if the application's strings are
8757 translated into other languages, but each arg() will still replace
8758 the lowest-numbered unreplaced place-marker, no matter where it
8759 appears. Also, if place-marker \c %i appears more than once in the
8760 string, arg() replaces all of them.
8761
8762 If there is no unreplaced place-marker remaining, a warning message
8763 is printed and the result is undefined. Place-marker numbers must be
8764 in the range 1 to 99.
8765
8766 \note In Qt versions prior to 6.9, this function was overloaded on
8767 \c{char}, QChar, QString, QStringView, and QLatin1StringView and in some
8768 cases, \c{wchar_t} and \c{char16_t} arguments would resolve to the integer
8769 overloads. In Qt versions prior to 5.10, this function lacked the
8770 QStringView and QLatin1StringView overloads.
8771*/
8772QString QString::arg_impl(QAnyStringView a, int fieldWidth, QChar fillChar) const
8773{
8774 ArgEscapeData d = findArgEscapes(*this);
8775
8776 if (Q_UNLIKELY(d.occurrences == 0)) {
8777 qWarning("QString::arg: Argument missing: \"%ls\", \"%ls\"", qUtf16Printable(*this),
8778 qUtf16Printable(a.toString()));
8779 return *this;
8780 }
8781 struct {
8782 QVarLengthArray<char16_t> out;
8783 QStringView operator()(QStringView in) noexcept { return in; }
8784 QStringView operator()(QLatin1StringView in)
8785 {
8786 out.resize(in.size());
8787 qt_from_latin1(out.data(), in.data(), size_t(in.size()));
8788 return out;
8789 }
8790 QStringView operator()(QUtf8StringView in)
8791 {
8792 out.resize(in.size());
8793 return QStringView{out.data(), QUtf8::convertToUnicode(out.data(), in)};
8794 }
8795 } convert;
8796
8797 QStringView sv = a.visit(std::ref(convert));
8798 return replaceArgEscapes(*this, d, fieldWidth, sv, sv, fillChar);
8799}
8800
8801/*!
8802 \fn template <typename T, QString::if_integral_non_char<T> = true> QString QString::arg(T a, int fieldWidth, int base, QChar fillChar) const
8803 \overload arg()
8804
8805 The \a a argument is expressed in base \a base, which is 10 by
8806 default and must be between 2 and 36. For bases other than 10, \a a
8807 is treated as an unsigned integer.
8808
8809 \a fieldWidth specifies the minimum amount of space that \a a is
8810 padded to and filled with the character \a fillChar. A positive
8811 value produces right-aligned text; a negative value produces
8812 left-aligned text.
8813
8814 The '%' can be followed by an 'L', in which case the sequence is
8815 replaced with a localized representation of \a a. The conversion
8816 uses the default locale, set by QLocale::setDefault(). If no default
8817 locale was specified, the system locale is used. The 'L' flag is
8818 ignored if \a base is not 10.
8819
8820 \snippet qstring/main.cpp 12
8821 \snippet qstring/main.cpp 14
8822
8823 \note In Qt versions prior to 6.10.1, this function accepted arguments of
8824 types that implicitly convert to integral types. This is no longer supported,
8825 except for (unscoped) enums, because it also accepted types convertible to
8826 floating-point types, losing precision when those were printed as integers. A
8827 backwards-compatible fix is to cast such types to a C++ type whose displayed
8828 form matches your intent (\c int, \c float, ...).
8829
8830 \note In Qt versions prior to 6.9, this function was overloaded on various
8831 integral types and sometimes incorrectly accepted \c char and \c char16_t
8832 arguments.
8833
8834 \sa {Number formats}
8835*/
8836QString QString::arg_impl(qlonglong a, int fieldWidth, int base, QChar fillChar) const
8837{
8838 ArgEscapeData d = findArgEscapes(*this);
8839
8840 if (d.occurrences == 0) {
8841 qWarning("QString::arg: Argument missing: \"%ls\", %llu", qUtf16Printable(*this), a);
8842 return *this;
8843 }
8844
8845 unsigned flags = QLocaleData::NoFlags;
8846 // ZeroPadded sorts out left-padding when the fill is zero, to the right of sign:
8847 if (fillChar == u'0')
8848 flags = QLocaleData::ZeroPadded;
8849
8850 QString arg;
8851 if (d.occurrences > d.locale_occurrences) {
8852 arg = QLocaleData::c()->longLongToString(a, -1, base, fieldWidth, flags);
8853 Q_ASSERT(fillChar != u'0' || fieldWidth <= arg.size());
8854 }
8855
8856 QString localeArg;
8857 if (d.locale_occurrences > 0) {
8858 QLocale locale;
8859 if (!(locale.numberOptions() & QLocale::OmitGroupSeparator))
8860 flags |= QLocaleData::GroupDigits;
8861 localeArg = locale.d->m_data->longLongToString(a, -1, base, fieldWidth, flags);
8862 Q_ASSERT(fillChar != u'0' || fieldWidth <= localeArg.size());
8863 }
8864
8865 return replaceArgEscapes(*this, d, fieldWidth, arg, localeArg, fillChar);
8866}
8867
8868QString QString::arg_impl(qulonglong a, int fieldWidth, int base, QChar fillChar) const
8869{
8870 ArgEscapeData d = findArgEscapes(*this);
8871
8872 if (d.occurrences == 0) {
8873 qWarning("QString::arg: Argument missing: \"%ls\", %lld", qUtf16Printable(*this), a);
8874 return *this;
8875 }
8876
8877 unsigned flags = QLocaleData::NoFlags;
8878 // ZeroPadded sorts out left-padding when the fill is zero, to the right of sign:
8879 if (fillChar == u'0')
8880 flags = QLocaleData::ZeroPadded;
8881
8882 QString arg;
8883 if (d.occurrences > d.locale_occurrences) {
8884 arg = QLocaleData::c()->unsLongLongToString(a, -1, base, fieldWidth, flags);
8885 Q_ASSERT(fillChar != u'0' || fieldWidth <= arg.size());
8886 }
8887
8888 QString localeArg;
8889 if (d.locale_occurrences > 0) {
8890 QLocale locale;
8891 if (!(locale.numberOptions() & QLocale::OmitGroupSeparator))
8892 flags |= QLocaleData::GroupDigits;
8893 localeArg = locale.d->m_data->unsLongLongToString(a, -1, base, fieldWidth, flags);
8894 Q_ASSERT(fillChar != u'0' || fieldWidth <= localeArg.size());
8895 }
8896
8897 return replaceArgEscapes(*this, d, fieldWidth, arg, localeArg, fillChar);
8898}
8899
8900/*!
8901 \fn template <typename T, QString::if_floating_point<T> = true> QString QString::arg(T a, int fieldWidth, char format, int precision, QChar fillChar) const
8902 \overload arg()
8903
8904 Argument \a a is formatted according to the specified \a format and
8905 \a precision. See \l{Floating-point Formats} for details.
8906
8907 \a fieldWidth specifies the minimum amount of space that \a a is
8908 padded to and filled with the character \a fillChar. A positive
8909 value produces right-aligned text; a negative value produces
8910 left-aligned text.
8911
8912 \snippet code/src_corelib_text_qstring.cpp 2
8913
8914 \note In Qt versions prior to 6.9, this function was a regular function
8915 taking \c double. As a consequence of being a template function now, it no
8916 longer accepts arguments that merely implicitly convert to floating-point
8917 types. A backwards-compatible fix is to cast such types to one of the C++
8918 floating-point types.
8919
8920 \sa QLocale::toString(), QLocale::FloatingPointPrecisionOption, {Number formats}
8921*/
8922QString QString::arg_impl(double a, int fieldWidth, char format, int precision, QChar fillChar) const
8923{
8924 ArgEscapeData d = findArgEscapes(*this);
8925
8926 if (d.occurrences == 0) {
8927 qWarning("QString::arg: Argument missing: \"%ls\", %g", qUtf16Printable(*this), a);
8928 return *this;
8929 }
8930
8931 unsigned flags = QLocaleData::NoFlags;
8932 // ZeroPadded sorts out left-padding when the fill is zero, to the right of sign:
8933 if (fillChar == u'0')
8934 flags |= QLocaleData::ZeroPadded;
8935
8936 if (isAsciiUpper(format))
8937 flags |= QLocaleData::CapitalEorX;
8938
8939 QLocaleData::DoubleForm form = QLocaleData::DFDecimal;
8940 switch (QtMiscUtils::toAsciiLower(format)) {
8941 case 'f':
8942 form = QLocaleData::DFDecimal;
8943 break;
8944 case 'e':
8945 form = QLocaleData::DFExponent;
8946 break;
8947 case 'g':
8948 form = QLocaleData::DFSignificantDigits;
8949 break;
8950 default:
8951#if defined(QT_CHECK_RANGE)
8952 qWarning("QString::arg: Invalid format char '%c'", format);
8953#endif
8954 break;
8955 }
8956
8957 QString arg;
8958 if (d.occurrences > d.locale_occurrences) {
8959 arg = QLocaleData::c()->doubleToString(a, precision, form, fieldWidth,
8960 flags | QLocaleData::ZeroPadExponent);
8961 Q_ASSERT(fillChar != u'0' || !qt_is_finite(a)
8962 || fieldWidth <= arg.size());
8963 }
8964
8965 QString localeArg;
8966 if (d.locale_occurrences > 0) {
8967 QLocale locale;
8968
8969 const QLocale::NumberOptions numberOptions = locale.numberOptions();
8970 if (!(numberOptions & QLocale::OmitGroupSeparator))
8971 flags |= QLocaleData::GroupDigits;
8972 if (!(numberOptions & QLocale::OmitLeadingZeroInExponent))
8973 flags |= QLocaleData::ZeroPadExponent;
8974 if (numberOptions & QLocale::IncludeTrailingZeroesAfterDot)
8975 flags |= QLocaleData::AddTrailingZeroes;
8976 localeArg = locale.d->m_data->doubleToString(a, precision, form, fieldWidth, flags);
8977 Q_ASSERT(fillChar != u'0' || !qt_is_finite(a)
8978 || fieldWidth <= localeArg.size());
8979 }
8980
8981 return replaceArgEscapes(*this, d, fieldWidth, arg, localeArg, fillChar);
8982}
8983
8984static inline char16_t to_unicode(const QChar c) { return c.unicode(); }
8985static inline char16_t to_unicode(const char c) { return QLatin1Char{c}.unicode(); }
8986
8987template <typename Char>
8988static int getEscape(const Char *uc, qsizetype *pos, qsizetype len)
8989{
8990 qsizetype i = *pos;
8991 ++i;
8992 if (i < len && uc[i] == u'L')
8993 ++i;
8994 if (i < len) {
8995 int escape = to_unicode(uc[i]) - '0';
8996 if (uint(escape) >= 10U)
8997 return -1;
8998 ++i;
8999 if (i < len) {
9000 // there's a second digit
9001 int digit = to_unicode(uc[i]) - '0';
9002 if (uint(digit) < 10U) {
9003 escape = (escape * 10) + digit;
9004 ++i;
9005 }
9006 }
9007 *pos = i;
9008 return escape;
9009 }
9010 return -1;
9011}
9012
9013/*
9014 Algorithm for multiArg:
9015
9016 1. Parse the string as a sequence of verbatim text and placeholders (%L?\d{,3}).
9017 The L is parsed and accepted for compatibility with non-multi-arg, but since
9018 multiArg only accepts strings as replacements, the localization request can
9019 be safely ignored.
9020 2. The result of step (1) is a list of (string-ref,int)-tuples. The string-ref
9021 either points at text to be copied verbatim (in which case the int is -1),
9022 or, initially, at the textual representation of the placeholder. In that case,
9023 the int contains the numerical number as parsed from the placeholder.
9024 3. Next, collect all the non-negative ints found, sort them in ascending order and
9025 remove duplicates.
9026 3a. If the result has more entries than multiArg() was given replacement strings,
9027 we have found placeholders we can't satisfy with replacement strings. That is
9028 fine (there could be another .arg() call coming after this one), so just
9029 truncate the result to the number of actual multiArg() replacement strings.
9030 3b. If the result has less entries than multiArg() was given replacement strings,
9031 the string is missing placeholders. This is an error that the user should be
9032 warned about.
9033 4. The result of step (3) is a mapping from the index of any replacement string to
9034 placeholder number. This is the wrong way around, but since placeholder
9035 numbers could get as large as 999, while we typically don't have more than 9
9036 replacement strings, we trade 4K of sparsely-used memory for doing a reverse lookup
9037 each time we need to map a placeholder number to a replacement string index
9038 (that's a linear search; but still *much* faster than using an associative container).
9039 5. Next, for each of the tuples found in step (1), do the following:
9040 5a. If the int is negative, do nothing.
9041 5b. Otherwise, if the int is found in the result of step (3) at index I, replace
9042 the string-ref with a string-ref for the (complete) I'th replacement string.
9043 5c. Otherwise, do nothing.
9044 6. Concatenate all string refs into a single result string.
9045*/
9046
9047namespace {
9048struct Part
9049{
9050 Part() = default; // for QVarLengthArray; do not use
9051 constexpr Part(QAnyStringView s, int num = -1)
9052 : string{s}, number{num} {}
9053
9054 void reset(QAnyStringView s) noexcept { *this = {s, number}; }
9055
9056 QAnyStringView string;
9057 int number;
9058};
9059} // unnamed namespace
9060
9062
9063namespace {
9064
9065enum { ExpectedParts = 32 };
9066
9067typedef QVarLengthArray<Part, ExpectedParts> ParseResult;
9068typedef QVarLengthArray<int, ExpectedParts/2> ArgIndexToPlaceholderMap;
9069
9070template <typename StringView>
9071static ParseResult parseMultiArgFormatString_impl(StringView s)
9072{
9073 ParseResult result;
9074
9075 const auto uc = s.data();
9076 const auto len = s.size();
9077 const auto end = len - 1;
9078 qsizetype i = 0;
9079 qsizetype last = 0;
9080
9081 while (i < end) {
9082 if (uc[i] == u'%') {
9083 qsizetype percent = i;
9084 int number = getEscape(uc, &i, len);
9085 if (number != -1) {
9086 if (last != percent)
9087 result.push_back(Part{s.sliced(last, percent - last)}); // literal text (incl. failed placeholders)
9088 result.push_back(Part{s.sliced(percent, i - percent), number}); // parsed placeholder
9089 last = i;
9090 continue;
9091 }
9092 }
9093 ++i;
9094 }
9095
9096 if (last < len)
9097 result.push_back(Part{s.sliced(last, len - last)}); // trailing literal text
9098
9099 return result;
9100}
9101
9102static ParseResult parseMultiArgFormatString(QAnyStringView s)
9103{
9104 return s.visit([] (auto s) { return parseMultiArgFormatString_impl(s); });
9105}
9106
9107static ArgIndexToPlaceholderMap makeArgIndexToPlaceholderMap(const ParseResult &parts)
9108{
9109 ArgIndexToPlaceholderMap result;
9110
9111 for (const Part &part : parts) {
9112 if (part.number >= 0)
9113 result.push_back(part.number);
9114 }
9115
9116 std::sort(result.begin(), result.end());
9117 result.erase(std::unique(result.begin(), result.end()),
9118 result.end());
9119
9120 return result;
9121}
9122
9123static qsizetype resolveStringRefsAndReturnTotalSize(ParseResult &parts, const ArgIndexToPlaceholderMap &argIndexToPlaceholderMap, const QtPrivate::ArgBase *args[])
9124{
9125 using namespace QtPrivate;
9126 qsizetype totalSize = 0;
9127 for (Part &part : parts) {
9128 if (part.number != -1) {
9129 const auto it = std::find(argIndexToPlaceholderMap.begin(), argIndexToPlaceholderMap.end(), part.number);
9130 if (it != argIndexToPlaceholderMap.end()) {
9131 const auto &arg = *args[it - argIndexToPlaceholderMap.begin()];
9132 switch (arg.tag) {
9133 case ArgBase::L1:
9134 part.reset(static_cast<const QLatin1StringArg&>(arg).string);
9135 break;
9136 case ArgBase::Any:
9137 part.reset(static_cast<const QAnyStringArg&>(arg).string);
9138 break;
9139 case ArgBase::U16:
9140 part.reset(static_cast<const QStringViewArg&>(arg).string);
9141 break;
9142 }
9143 }
9144 }
9145 totalSize += part.string.size();
9146 }
9147 return totalSize;
9148}
9149
9150} // unnamed namespace
9151
9152QString QtPrivate::argToQString(QAnyStringView pattern, size_t numArgs, const ArgBase **args)
9153{
9154 // Step 1-2 above
9155 ParseResult parts = parseMultiArgFormatString(pattern);
9156
9157 // 3-4
9158 ArgIndexToPlaceholderMap argIndexToPlaceholderMap = makeArgIndexToPlaceholderMap(parts);
9159
9160 if (static_cast<size_t>(argIndexToPlaceholderMap.size()) > numArgs) // 3a
9161 argIndexToPlaceholderMap.resize(qsizetype(numArgs));
9162 else if (Q_UNLIKELY(static_cast<size_t>(argIndexToPlaceholderMap.size()) < numArgs)) // 3b
9163 qWarning("QString::arg: %d argument(s) missing in %ls",
9164 int(numArgs - argIndexToPlaceholderMap.size()), qUtf16Printable(pattern.toString()));
9165
9166 // 5
9167 const qsizetype totalSize = resolveStringRefsAndReturnTotalSize(parts, argIndexToPlaceholderMap, args);
9168
9169 // 6:
9170 QString result(totalSize, Qt::Uninitialized);
9171 auto out = const_cast<QChar*>(result.constData());
9172
9173 struct Concatenate {
9174 QChar *out;
9175 QChar *operator()(QLatin1String part) noexcept
9176 {
9177 if (part.size()) {
9178 qt_from_latin1(reinterpret_cast<char16_t*>(out),
9179 part.data(), part.size());
9180 }
9181 return out + part.size();
9182 }
9183 QChar *operator()(QUtf8StringView part) noexcept
9184 {
9185 return QUtf8::convertToUnicode(out, part);
9186 }
9187 QChar *operator()(QStringView part) noexcept
9188 {
9189 if (part.size())
9190 memcpy(out, part.data(), part.size() * sizeof(QChar));
9191 return out + part.size();
9192 }
9193 };
9194
9195 for (const Part &part : parts)
9196 out = part.string.visit(Concatenate{out});
9197
9198 // UTF-8 decoding may have caused an overestimate of totalSize - correct it:
9199 result.truncate(out - result.cbegin());
9200
9201 return result;
9202}
9203
9204/*! \fn bool QString::isRightToLeft() const
9205
9206 Returns \c true if the string is read right to left.
9207
9208 \sa QStringView::isRightToLeft()
9209*/
9210bool QString::isRightToLeft() const
9211{
9212 return QtPrivate::isRightToLeft(QStringView(*this));
9213}
9214
9215/*!
9216 \fn bool QString::isValidUtf16() const noexcept
9217 \since 5.15
9218
9219 Returns \c true if the string contains valid UTF-16 encoded data,
9220 or \c false otherwise.
9221
9222 Note that this function does not perform any special validation of the
9223 data; it merely checks if it can be successfully decoded from UTF-16.
9224 The data is assumed to be in host byte order; the presence of a BOM
9225 is meaningless.
9226
9227 \sa QStringView::isValidUtf16()
9228*/
9229
9230/*! \fn QChar *QString::data()
9231
9232 Returns a pointer to the data stored in the QString. The pointer
9233 can be used to access and modify the characters that compose the
9234 string.
9235
9236 Unlike constData() and unicode(), the returned data is always
9237 '\\0'-terminated.
9238
9239 Example:
9240
9241 \snippet qstring/main.cpp 19
9242
9243 Note that the pointer remains valid only as long as the string is
9244 not modified by other means. For read-only access, constData() is
9245 faster because it never causes a \l{deep copy} to occur.
9246
9247 \sa constData(), operator[]()
9248*/
9249
9250/*! \fn const QChar *QString::data() const
9251
9252 \overload
9253
9254 \note The returned string may not be '\\0'-terminated.
9255 Use size() to determine the length of the array.
9256
9257 \sa fromRawData()
9258*/
9259
9260/*! \fn const QChar *QString::constData() const
9261
9262 Returns a pointer to the data stored in the QString. The pointer
9263 can be used to access the characters that compose the string.
9264
9265 Note that the pointer remains valid only as long as the string is
9266 not modified.
9267
9268 \note The returned string may not be '\\0'-terminated.
9269 Use size() to determine the length of the array.
9270
9271 \sa data(), operator[](), fromRawData()
9272*/
9273
9274/*! \fn void QString::push_front(const QString &other)
9275
9276 This function is provided for STL compatibility, prepending the
9277 given \a other string to the beginning of this string. It is
9278 equivalent to \c prepend(other).
9279
9280 \sa prepend()
9281*/
9282
9283/*! \fn void QString::push_front(QChar ch)
9284
9285 \overload
9286
9287 Prepends the given \a ch character to the beginning of this string.
9288*/
9289
9290/*! \fn void QString::push_back(const QString &other)
9291
9292 This function is provided for STL compatibility, appending the
9293 given \a other string onto the end of this string. It is
9294 equivalent to \c append(other).
9295
9296 \sa append()
9297*/
9298
9299/*! \fn void QString::push_back(QChar ch)
9300
9301 \overload
9302
9303 Appends the given \a ch character onto the end of this string.
9304*/
9305
9306/*!
9307 \since 6.1
9308
9309 Removes from the string the characters in the half-open range
9310 [ \a first , \a last ). Returns an iterator to the character
9311 immediately after the last erased character (i.e. the character
9312 referred to by \a last before the erase).
9313*/
9314QString::iterator QString::erase(QString::const_iterator first, QString::const_iterator last)
9315{
9316 const auto start = std::distance(cbegin(), first);
9317 const auto len = std::distance(first, last);
9318 remove(start, len);
9319 return begin() + start;
9320}
9321
9322/*!
9323 \fn QString::iterator QString::erase(QString::const_iterator it)
9324
9325 \overload
9326 \since 6.5
9327
9328 Removes the character denoted by \c it from the string.
9329 Returns an iterator to the character immediately after the
9330 erased character.
9331
9332 \code
9333 QString c = "abcdefg";
9334 auto it = c.erase(c.cbegin()); // c is now "bcdefg"; "it" points to "b"
9335 \endcode
9336*/
9337
9338/*! \fn void QString::shrink_to_fit()
9339 \since 5.10
9340
9341 This function is provided for STL compatibility. It is
9342 equivalent to squeeze().
9343
9344 \sa squeeze()
9345*/
9346
9347/*!
9348 \fn std::string QString::toStdString() const
9349
9350 Returns a std::string object with the data contained in this
9351 QString. The Unicode data is converted into 8-bit characters using
9352 the toUtf8() function.
9353
9354 This method is mostly useful to pass a QString to a function
9355 that accepts a std::string object.
9356
9357 \sa toLatin1(), toUtf8(), toLocal8Bit(), QByteArray::toStdString()
9358*/
9359std::string QString::toStdString() const
9360{
9361 std::string result;
9362 if (isEmpty())
9363 return result;
9364
9365 auto writeToBuffer = [this](char *out, size_t) {
9366 char *last = QUtf8::convertFromUnicode(out, *this);
9367 return last - out;
9368 };
9369 const size_t maxSize = size() * size_t{3}; // worst case for UTF-8 (does _not_ overflow!)
9370#ifdef __cpp_lib_string_resize_and_overwrite
9371 // C++23
9372 result.resize_and_overwrite(maxSize, writeToBuffer);
9373#else
9374 result.resize(maxSize);
9375 result.resize(writeToBuffer(result.data(), result.size()));
9376#endif
9377 return result;
9378}
9379
9380/*!
9381 \fn QString QString::fromRawData(const char16_t *unicode, qsizetype size)
9382 \since 6.10
9383
9384 Constructs a QString that uses the first \a size Unicode characters
9385 in the array \a unicode. The data in \a unicode is \e not
9386 copied. The caller must be able to guarantee that \a unicode will
9387 not be deleted or modified as long as the QString (or an
9388 unmodified copy of it) exists.
9389
9390 Any attempts to modify the QString or copies of it will cause it
9391 to create a deep copy of the data, ensuring that the raw data
9392 isn't modified.
9393
9394 Here is an example of how we can use a QRegularExpression on raw data in
9395 memory without requiring to copy the data into a QString:
9396
9397 \snippet qstring/main.cpp 22
9398 \snippet qstring/main.cpp 23
9399
9400 \warning A string created with fromRawData() is \e not
9401 '\\0'-terminated, unless the raw data contains a '\\0' character
9402 at position \a size. This means unicode() will \e not return a
9403 '\\0'-terminated string (although utf16() does, at the cost of
9404 copying the raw data).
9405
9406 \sa fromUtf16(), setRawData(), data(), constData(),
9407 nullTerminate(), nullTerminated()
9408*/
9409
9410/*!
9411 \fn QString QString::fromRawData(const QChar *unicode, qsizetype size)
9412 \overload
9413*/
9414
9415/*!
9416 \since 4.7
9417
9418 Resets the QString to use the first \a size Unicode characters
9419 in the array \a unicode. The data in \a unicode is \e not
9420 copied. The caller must be able to guarantee that \a unicode will
9421 not be deleted or modified as long as the QString (or an
9422 unmodified copy of it) exists.
9423
9424 This function can be used instead of fromRawData() to re-use
9425 existings QString objects to save memory re-allocations.
9426
9427 \sa fromRawData(), nullTerminate(), nullTerminated()
9428*/
9429QString &QString::setRawData(const QChar *unicode, qsizetype size)
9430{
9431 if (!unicode || !size) {
9432 clear();
9433 }
9434 *this = fromRawData(unicode, size);
9435 return *this;
9436}
9437
9438/*! \fn QString QString::fromStdU16String(const std::u16string &str)
9439 \since 5.5
9440
9441 \include qstring.cpp {from-std-string} {UTF-16} {fromUtf16()}
9442
9443 \sa fromUtf16(), fromStdWString(), fromStdU32String()
9444*/
9445
9446/*!
9447 \fn std::u16string QString::toStdU16String() const
9448 \since 5.5
9449
9450 Returns a std::u16string object with the data contained in this
9451 QString. The Unicode data is the same as returned by the utf16()
9452 method.
9453
9454 \sa utf16(), toStdWString(), toStdU32String()
9455*/
9456
9457/*! \fn QString QString::fromStdU32String(const std::u32string &str)
9458 \since 5.5
9459
9460 \include qstring.cpp {from-std-string} {UTF-32} {fromUcs4()}
9461
9462 \sa fromUcs4(), fromStdWString(), fromStdU16String()
9463*/
9464
9465/*!
9466 \fn std::u32string QString::toStdU32String() const
9467 \since 5.5
9468
9469 Returns a std::u32string object with the data contained in this
9470 QString. The Unicode data is the same as returned by the toUcs4()
9471 method.
9472
9473 \sa toUcs4(), toStdWString(), toStdU16String()
9474*/
9475
9476#if !defined(QT_NO_DATASTREAM)
9477/*!
9478 \fn QDataStream &operator<<(QDataStream &stream, const QString &string)
9479 \relates QString
9480
9481 Writes the given \a string to the specified \a stream.
9482
9483 \sa {Serializing Qt Data Types}
9484*/
9485
9486QDataStream &operator<<(QDataStream &out, const QString &str)
9487{
9488 if (out.version() == 1) {
9489 out << str.toLatin1();
9490 } else {
9491 if (!str.isNull() || out.version() < 3) {
9492 if ((out.byteOrder() == QDataStream::BigEndian) == (QSysInfo::ByteOrder == QSysInfo::BigEndian)) {
9493 out.writeBytes(reinterpret_cast<const char *>(str.unicode()),
9494 static_cast<qsizetype>(sizeof(QChar) * str.size()));
9495 } else {
9496 QVarLengthArray<char16_t> buffer(str.size());
9497 qbswap<sizeof(char16_t)>(str.constData(), str.size(), buffer.data());
9498 out.writeBytes(reinterpret_cast<const char *>(buffer.data()),
9499 static_cast<qsizetype>(sizeof(char16_t) * buffer.size()));
9500 }
9501 } else {
9502 QDataStream::writeQSizeType(out, -1); // write null marker
9503 }
9504 }
9505 return out;
9506}
9507
9508/*!
9509 \fn QDataStream &operator>>(QDataStream &stream, QString &string)
9510 \relates QString
9511
9512 Reads a string from the specified \a stream into the given \a string.
9513
9514 \sa {Serializing Qt Data Types}
9515*/
9516
9517QDataStream &operator>>(QDataStream &in, QString &str)
9518{
9519 if (in.version() == 1) {
9520 QByteArray l;
9521 in >> l;
9522 str = QString::fromLatin1(l);
9523 } else {
9524 qint64 size = QDataStream::readQSizeType(in);
9525 qsizetype bytes = size;
9526 if (size != bytes || size < -1) {
9527 str.clear();
9528 in.setStatus(QDataStream::SizeLimitExceeded);
9529 return in;
9530 }
9531 if (bytes == -1) { // null string
9532 str = QString();
9533 } else if (bytes > 0) {
9534 if (bytes & 0x1) {
9535 str.clear();
9536 in.setStatus(QDataStream::ReadCorruptData);
9537 return in;
9538 }
9539
9540 const qsizetype Step = 1024 * 1024;
9541 qsizetype len = bytes / 2;
9542 qsizetype allocated = 0;
9543
9544 while (allocated < len) {
9545 int blockSize = qMin(Step, len - allocated);
9546 str.resize(allocated + blockSize);
9547 if (in.readRawData(reinterpret_cast<char *>(str.data()) + allocated * 2,
9548 blockSize * 2) != blockSize * 2) {
9549 str.clear();
9550 in.setStatus(QDataStream::ReadPastEnd);
9551 return in;
9552 }
9553 allocated += blockSize;
9554 }
9555
9556 if ((in.byteOrder() == QDataStream::BigEndian)
9557 != (QSysInfo::ByteOrder == QSysInfo::BigEndian)) {
9558 char16_t *data = reinterpret_cast<char16_t *>(str.data());
9559 qbswap<sizeof(*data)>(data, len, data);
9560 }
9561 } else {
9562 str = QString(QLatin1StringView(""));
9563 }
9564 }
9565 return in;
9566}
9567#endif // QT_NO_DATASTREAM
9568
9569/*!
9570 \typedef QString::Data
9571 \internal
9572*/
9573
9574/*!
9575 \typedef QString::DataPtr
9576 \internal
9577*/
9578
9579/*!
9580 \fn DataPtr & QString::data_ptr()
9581 \internal
9582*/
9583
9584/*!
9585 \since 5.11
9586 \internal
9587 \relates QStringView
9588
9589 Returns \c true if the string is read right to left.
9590
9591 \sa QString::isRightToLeft()
9592*/
9593bool QtPrivate::isRightToLeft(QStringView string) noexcept
9594{
9595 int isolateLevel = 0;
9596
9597 for (QStringIterator i(string); i.hasNext();) {
9598 const char32_t c = i.next();
9599
9600 switch (QChar::direction(c)) {
9601 case QChar::DirRLI:
9602 case QChar::DirLRI:
9603 case QChar::DirFSI:
9604 ++isolateLevel;
9605 break;
9606 case QChar::DirPDI:
9607 if (isolateLevel)
9608 --isolateLevel;
9609 break;
9610 case QChar::DirL:
9611 if (isolateLevel)
9612 break;
9613 return false;
9614 case QChar::DirR:
9615 case QChar::DirAL:
9616 if (isolateLevel)
9617 break;
9618 return true;
9619 case QChar::DirEN:
9620 case QChar::DirES:
9621 case QChar::DirET:
9622 case QChar::DirAN:
9623 case QChar::DirCS:
9624 case QChar::DirB:
9625 case QChar::DirS:
9626 case QChar::DirWS:
9627 case QChar::DirON:
9628 case QChar::DirLRE:
9629 case QChar::DirLRO:
9630 case QChar::DirRLE:
9631 case QChar::DirRLO:
9632 case QChar::DirPDF:
9633 case QChar::DirNSM:
9634 case QChar::DirBN:
9635 break;
9636 }
9637 }
9638 return false;
9639}
9640
9641qsizetype QtPrivate::count(QStringView haystack, QStringView needle, Qt::CaseSensitivity cs) noexcept
9642{
9643 qsizetype num = 0;
9644 qsizetype i = -1;
9645 if (haystack.size() > 500 && needle.size() > 5) {
9646 QStringMatcher matcher(needle, cs);
9647 while ((i = matcher.indexIn(haystack, i + 1)) != -1)
9648 ++num;
9649 } else {
9650 while ((i = QtPrivate::findString(haystack, i + 1, needle, cs)) != -1)
9651 ++num;
9652 }
9653 return num;
9654}
9655
9656qsizetype QtPrivate::count(QStringView haystack, QChar needle, Qt::CaseSensitivity cs) noexcept
9657{
9658 if (cs == Qt::CaseSensitive)
9659 return std::count(haystack.cbegin(), haystack.cend(), needle);
9660
9661 needle = foldCase(needle);
9662 return std::count_if(haystack.cbegin(), haystack.cend(),
9663 [needle](const QChar c) { return foldAndCompare(c, needle); });
9664}
9665
9666qsizetype QtPrivate::count(QLatin1StringView haystack, QLatin1StringView needle, Qt::CaseSensitivity cs)
9667{
9668 qsizetype num = 0;
9669 qsizetype i = -1;
9670
9671 QLatin1StringMatcher matcher(needle, cs);
9672 while ((i = matcher.indexIn(haystack, i + 1)) != -1)
9673 ++num;
9674
9675 return num;
9676}
9677
9678qsizetype QtPrivate::count(QLatin1StringView haystack, QStringView needle, Qt::CaseSensitivity cs)
9679{
9680 if (haystack.size() < needle.size())
9681 return 0;
9682
9683 if (!QtPrivate::isLatin1(needle)) // won't find non-L1 UTF-16 needles in a L1 haystack!
9684 return 0;
9685
9686 qsizetype num = 0;
9687 qsizetype i = -1;
9688
9689 QVarLengthArray<uchar> s(needle.size());
9690 qt_to_latin1_unchecked(s.data(), needle.utf16(), needle.size());
9691
9692 QLatin1StringMatcher matcher(QLatin1StringView(reinterpret_cast<char *>(s.data()), s.size()),
9693 cs);
9694 while ((i = matcher.indexIn(haystack, i + 1)) != -1)
9695 ++num;
9696
9697 return num;
9698}
9699
9700qsizetype QtPrivate::count(QStringView haystack, QLatin1StringView needle, Qt::CaseSensitivity cs)
9701{
9702 if (haystack.size() < needle.size())
9703 return -1;
9704
9705 QVarLengthArray<char16_t> s = qt_from_latin1_to_qvla(needle);
9706 return QtPrivate::count(haystack, QStringView(s.data(), s.size()), cs);
9707}
9708
9709qsizetype QtPrivate::count(QLatin1StringView haystack, QChar needle, Qt::CaseSensitivity cs) noexcept
9710{
9711 // non-L1 needles cannot possibly match in L1-only haystacks
9712 if (needle.unicode() > 0xff)
9713 return 0;
9714
9715 if (cs == Qt::CaseSensitive) {
9716 return std::count(haystack.cbegin(), haystack.cend(), needle.toLatin1());
9717 } else {
9718 return std::count_if(haystack.cbegin(), haystack.cend(),
9719 CaseInsensitiveL1::matcher(needle.toLatin1()));
9720 }
9721}
9722
9723/*!
9724 \fn bool QtPrivate::startsWith(QStringView haystack, QStringView needle, Qt::CaseSensitivity cs)
9725 \since 5.10
9726 \fn bool QtPrivate::startsWith(QStringView haystack, QLatin1StringView needle, Qt::CaseSensitivity cs)
9727 \since 5.10
9728 \fn bool QtPrivate::startsWith(QLatin1StringView haystack, QStringView needle, Qt::CaseSensitivity cs)
9729 \since 5.10
9730 \fn bool QtPrivate::startsWith(QLatin1StringView haystack, QLatin1StringView needle, Qt::CaseSensitivity cs)
9731 \since 5.10
9732 \internal
9733 \relates QStringView
9734
9735 Returns \c true if \a haystack starts with \a needle,
9736 otherwise returns \c false.
9737
9738 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
9739
9740 \sa QtPrivate::endsWith(), QString::endsWith(), QStringView::endsWith(), QLatin1StringView::endsWith()
9741*/
9742
9743bool QtPrivate::startsWith(QStringView haystack, QStringView needle, Qt::CaseSensitivity cs) noexcept
9744{
9745 return qt_starts_with_impl(haystack, needle, cs);
9746}
9747
9748bool QtPrivate::startsWith(QStringView haystack, QLatin1StringView needle, Qt::CaseSensitivity cs) noexcept
9749{
9750 return qt_starts_with_impl(haystack, needle, cs);
9751}
9752
9753bool QtPrivate::startsWith(QLatin1StringView haystack, QStringView needle, Qt::CaseSensitivity cs) noexcept
9754{
9755 return qt_starts_with_impl(haystack, needle, cs);
9756}
9757
9758bool QtPrivate::startsWith(QLatin1StringView haystack, QLatin1StringView needle, Qt::CaseSensitivity cs) noexcept
9759{
9760 return qt_starts_with_impl(haystack, needle, cs);
9761}
9762
9763/*!
9764 \fn bool QtPrivate::endsWith(QStringView haystack, QStringView needle, Qt::CaseSensitivity cs)
9765 \since 5.10
9766 \fn bool QtPrivate::endsWith(QStringView haystack, QLatin1StringView needle, Qt::CaseSensitivity cs)
9767 \since 5.10
9768 \fn bool QtPrivate::endsWith(QLatin1StringView haystack, QStringView needle, Qt::CaseSensitivity cs)
9769 \since 5.10
9770 \fn bool QtPrivate::endsWith(QLatin1StringView haystack, QLatin1StringView needle, Qt::CaseSensitivity cs)
9771 \since 5.10
9772 \internal
9773 \relates QStringView
9774
9775 Returns \c true if \a haystack ends with \a needle,
9776 otherwise returns \c false.
9777
9778 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
9779
9780 \sa QtPrivate::startsWith(), QString::endsWith(), QStringView::endsWith(), QLatin1StringView::endsWith()
9781*/
9782
9783bool QtPrivate::endsWith(QStringView haystack, QStringView needle, Qt::CaseSensitivity cs) noexcept
9784{
9785 return qt_ends_with_impl(haystack, needle, cs);
9786}
9787
9788bool QtPrivate::endsWith(QStringView haystack, QLatin1StringView needle, Qt::CaseSensitivity cs) noexcept
9789{
9790 return qt_ends_with_impl(haystack, needle, cs);
9791}
9792
9793bool QtPrivate::endsWith(QLatin1StringView haystack, QStringView needle, Qt::CaseSensitivity cs) noexcept
9794{
9795 return qt_ends_with_impl(haystack, needle, cs);
9796}
9797
9798bool QtPrivate::endsWith(QLatin1StringView haystack, QLatin1StringView needle, Qt::CaseSensitivity cs) noexcept
9799{
9800 return qt_ends_with_impl(haystack, needle, cs);
9801}
9802
9803qsizetype QtPrivate::findString(QStringView haystack0, qsizetype from, QStringView needle0, Qt::CaseSensitivity cs) noexcept
9804{
9805 const qsizetype l = haystack0.size();
9806 const qsizetype sl = needle0.size();
9807 if (sl == 1)
9808 return findString(haystack0, from, needle0[0], cs);
9809 if (from < 0)
9810 from += l;
9811 if (std::size_t(sl + from) > std::size_t(l))
9812 return -1;
9813 if (!sl)
9814 return from;
9815 if (!l)
9816 return -1;
9817
9818 /*
9819 We use the Boyer-Moore algorithm in cases where the overhead
9820 for the skip table should pay off, otherwise we use a simple
9821 hash function.
9822 */
9823 if (l > 500 && sl > 5)
9824 return qFindStringBoyerMoore(haystack0, from, needle0, cs);
9825
9826 auto sv = [sl](const char16_t *v) { return QStringView(v, sl); };
9827 /*
9828 We use some hashing for efficiency's sake. Instead of
9829 comparing strings, we compare the hash value of str with that
9830 of a part of this QString. Only if that matches, we call
9831 qt_string_compare().
9832 */
9833 const char16_t *needle = needle0.utf16();
9834 const char16_t *haystack = haystack0.utf16() + from;
9835 const char16_t *end = haystack0.utf16() + (l - sl);
9836 const qregisteruint sl_minus_1 = sl - 1;
9837 qregisteruint hashNeedle = 0, hashHaystack = 0;
9838 qsizetype idx;
9839
9840 if (cs == Qt::CaseSensitive) {
9841 for (idx = 0; idx < sl; ++idx) {
9842 hashNeedle = ((hashNeedle<<1) + needle[idx]);
9843 hashHaystack = ((hashHaystack<<1) + haystack[idx]);
9844 }
9845 hashHaystack -= haystack[sl_minus_1];
9846
9847 while (haystack <= end) {
9848 hashHaystack += haystack[sl_minus_1];
9849 if (hashHaystack == hashNeedle
9850 && QtPrivate::compareStrings(needle0, sv(haystack), Qt::CaseSensitive) == 0)
9851 return haystack - haystack0.utf16();
9852
9853 REHASH(*haystack);
9854 ++haystack;
9855 }
9856 } else {
9857 const char16_t *haystack_start = haystack0.utf16();
9858 for (idx = 0; idx < sl; ++idx) {
9859 hashNeedle = (hashNeedle<<1) + foldCase(needle + idx, needle);
9860 hashHaystack = (hashHaystack<<1) + foldCase(haystack + idx, haystack_start);
9861 }
9862 hashHaystack -= foldCase(haystack + sl_minus_1, haystack_start);
9863
9864 while (haystack <= end) {
9865 hashHaystack += foldCase(haystack + sl_minus_1, haystack_start);
9866 if (hashHaystack == hashNeedle
9867 && QtPrivate::compareStrings(needle0, sv(haystack), Qt::CaseInsensitive) == 0)
9868 return haystack - haystack0.utf16();
9869
9870 REHASH(foldCase(haystack, haystack_start));
9871 ++haystack;
9872 }
9873 }
9874 return -1;
9875}
9876
9877qsizetype QtPrivate::findString(QStringView haystack, qsizetype from, QLatin1StringView needle, Qt::CaseSensitivity cs) noexcept
9878{
9879 if (haystack.size() < needle.size())
9880 return -1;
9881
9882 QVarLengthArray<char16_t> s = qt_from_latin1_to_qvla(needle);
9883 return QtPrivate::findString(haystack, from, QStringView(reinterpret_cast<const QChar*>(s.constData()), s.size()), cs);
9884}
9885
9886qsizetype QtPrivate::findString(QLatin1StringView haystack, qsizetype from, QStringView needle, Qt::CaseSensitivity cs) noexcept
9887{
9888 if (haystack.size() < needle.size())
9889 return -1;
9890
9891 if (!QtPrivate::isLatin1(needle)) // won't find non-L1 UTF-16 needles in a L1 haystack!
9892 return -1;
9893
9894 if (needle.size() == 1) {
9895 const char n = needle.front().toLatin1();
9896 return QtPrivate::findString(haystack, from, QLatin1StringView(&n, 1), cs);
9897 }
9898
9899 QVarLengthArray<char> s(needle.size());
9900 qt_to_latin1_unchecked(reinterpret_cast<uchar *>(s.data()), needle.utf16(), needle.size());
9901 return QtPrivate::findString(haystack, from, QLatin1StringView(s.data(), s.size()), cs);
9902}
9903
9904qsizetype QtPrivate::findString(QLatin1StringView haystack, qsizetype from, QLatin1StringView needle, Qt::CaseSensitivity cs) noexcept
9905{
9906 if (from < 0)
9907 from += haystack.size();
9908 if (from < 0)
9909 return -1;
9910 qsizetype adjustedSize = haystack.size() - from;
9911 if (adjustedSize < needle.size())
9912 return -1;
9913 if (needle.size() == 0)
9914 return from;
9915
9916 if (cs == Qt::CaseSensitive) {
9917
9918 if (needle.size() == 1) {
9919 Q_ASSERT(haystack.data() != nullptr); // see size check above
9920 if (auto it = memchr(haystack.data() + from, needle.front().toLatin1(), adjustedSize))
9921 return static_cast<const char *>(it) - haystack.data();
9922 return -1;
9923 }
9924
9925 const QLatin1StringMatcher matcher(needle, Qt::CaseSensitivity::CaseSensitive);
9926 return matcher.indexIn(haystack, from);
9927 }
9928
9929 // If the needle is sufficiently small we simply iteratively search through
9930 // the haystack. When the needle is too long we use a boyer-moore searcher
9931 // from the standard library, if available. If it is not available then the
9932 // QLatin1Strings are converted to QString and compared as such. Though
9933 // initialization is slower the boyer-moore search it employs still makes up
9934 // for it when haystack and needle are sufficiently long.
9935 // The needle size was chosen by testing various lengths using the
9936 // qstringtokenizer benchmark with the
9937 // "tokenize_qlatin1string_qlatin1string" test.
9938#ifdef Q_CC_MSVC
9939 const qsizetype threshold = 1;
9940#else
9941 const qsizetype threshold = 13;
9942#endif
9943 if (needle.size() <= threshold) {
9944 const auto begin = haystack.begin();
9945 const auto end = haystack.end() - needle.size() + 1;
9946 auto ciMatch = CaseInsensitiveL1::matcher(needle[0].toLatin1());
9947 const qsizetype nlen1 = needle.size() - 1;
9948 for (auto it = std::find_if(begin + from, end, ciMatch); it != end;
9949 it = std::find_if(it + 1, end, ciMatch)) {
9950 // In this comparison we skip the first character because we know it's a match
9951 if (!nlen1 || QLatin1StringView(it + 1, nlen1).compare(needle.sliced(1), cs) == 0)
9952 return std::distance(begin, it);
9953 }
9954 return -1;
9955 }
9956
9957 QLatin1StringMatcher matcher(needle, Qt::CaseSensitivity::CaseInsensitive);
9958 return matcher.indexIn(haystack, from);
9959}
9960
9961qsizetype QtPrivate::lastIndexOf(QStringView haystack, qsizetype from, char16_t needle, Qt::CaseSensitivity cs) noexcept
9962{
9963 return qLastIndexOf(haystack, QChar(needle), from, cs);
9964}
9965
9966qsizetype QtPrivate::lastIndexOf(QStringView haystack, qsizetype from, QStringView needle, Qt::CaseSensitivity cs) noexcept
9967{
9968 return qLastIndexOf(haystack, from, needle, cs);
9969}
9970
9971qsizetype QtPrivate::lastIndexOf(QStringView haystack, qsizetype from, QLatin1StringView needle, Qt::CaseSensitivity cs) noexcept
9972{
9973 return qLastIndexOf(haystack, from, needle, cs);
9974}
9975
9976qsizetype QtPrivate::lastIndexOf(QLatin1StringView haystack, qsizetype from, QStringView needle, Qt::CaseSensitivity cs) noexcept
9977{
9978 return qLastIndexOf(haystack, from, needle, cs);
9979}
9980
9981qsizetype QtPrivate::lastIndexOf(QLatin1StringView haystack, qsizetype from, QLatin1StringView needle, Qt::CaseSensitivity cs) noexcept
9982{
9983 return qLastIndexOf(haystack, from, needle, cs);
9984}
9985
9986#if QT_CONFIG(regularexpression)
9987qsizetype QtPrivate::indexOf(QStringView viewHaystack, const QString *stringHaystack, const QRegularExpression &re, qsizetype from, QRegularExpressionMatch *rmatch)
9988{
9989 if (!re.isValid()) {
9990 qtWarnAboutInvalidRegularExpression(re, "QString(View)", "indexOf");
9991 return -1;
9992 }
9993
9994 QRegularExpressionMatch match = stringHaystack
9995 ? re.match(*stringHaystack, from)
9996 : re.matchView(viewHaystack, from);
9997 if (match.hasMatch()) {
9998 const qsizetype ret = match.capturedStart();
9999 if (rmatch)
10000 *rmatch = std::move(match);
10001 return ret;
10002 }
10003
10004 return -1;
10005}
10006
10007qsizetype QtPrivate::indexOf(QStringView haystack, const QRegularExpression &re, qsizetype from, QRegularExpressionMatch *rmatch)
10008{
10009 return indexOf(haystack, nullptr, re, from, rmatch);
10010}
10011
10012qsizetype QtPrivate::lastIndexOf(QStringView viewHaystack, const QString *stringHaystack, const QRegularExpression &re, qsizetype from, QRegularExpressionMatch *rmatch)
10013{
10014 if (!re.isValid()) {
10015 qtWarnAboutInvalidRegularExpression(re, "QString(View)", "lastIndexOf");
10016 return -1;
10017 }
10018
10019 qsizetype endpos = (from < 0) ? (viewHaystack.size() + from + 1) : (from + 1);
10020 QRegularExpressionMatchIterator iterator = stringHaystack
10021 ? re.globalMatch(*stringHaystack)
10022 : re.globalMatchView(viewHaystack);
10023 qsizetype lastIndex = -1;
10024 while (iterator.hasNext()) {
10025 QRegularExpressionMatch match = iterator.next();
10026 qsizetype start = match.capturedStart();
10027 if (start < endpos) {
10028 lastIndex = start;
10029 if (rmatch)
10030 *rmatch = std::move(match);
10031 } else {
10032 break;
10033 }
10034 }
10035
10036 return lastIndex;
10037}
10038
10039qsizetype QtPrivate::lastIndexOf(QStringView haystack, const QRegularExpression &re, qsizetype from, QRegularExpressionMatch *rmatch)
10040{
10041 return lastIndexOf(haystack, nullptr, re, from, rmatch);
10042}
10043
10044bool QtPrivate::contains(QStringView viewHaystack, const QString *stringHaystack, const QRegularExpression &re, QRegularExpressionMatch *rmatch)
10045{
10046 if (!re.isValid()) {
10047 qtWarnAboutInvalidRegularExpression(re, "QString(View)", "contains");
10048 return false;
10049 }
10050 QRegularExpressionMatch m = stringHaystack
10051 ? re.match(*stringHaystack)
10052 : re.matchView(viewHaystack);
10053 bool hasMatch = m.hasMatch();
10054 if (hasMatch && rmatch)
10055 *rmatch = std::move(m);
10056 return hasMatch;
10057}
10058
10059bool QtPrivate::contains(QStringView haystack, const QRegularExpression &re, QRegularExpressionMatch *rmatch)
10060{
10061 return contains(haystack, nullptr, re, rmatch);
10062}
10063
10064qsizetype QtPrivate::count(QStringView haystack, const QRegularExpression &re)
10065{
10066 if (!re.isValid()) {
10067 qtWarnAboutInvalidRegularExpression(re, "QString(View)", "count");
10068 return 0;
10069 }
10070 qsizetype count = 0;
10071 qsizetype index = -1;
10072 qsizetype len = haystack.size();
10073 while (index <= len - 1) {
10074 QRegularExpressionMatch match = re.matchView(haystack, index + 1);
10075 if (!match.hasMatch())
10076 break;
10077 count++;
10078
10079 // Search again, from the next character after the beginning of this
10080 // capture. If the capture starts with a surrogate pair, both together
10081 // count as "one character".
10082 index = match.capturedStart();
10083 if (index < len && haystack[index].isHighSurrogate())
10084 ++index;
10085 }
10086 return count;
10087}
10088
10089#endif // QT_CONFIG(regularexpression)
10090
10091/*!
10092 \since 5.0
10093
10094 Converts a plain text string to an HTML string with
10095 HTML metacharacters \c{<}, \c{>}, \c{&}, and \c{"} replaced by HTML
10096 entities.
10097
10098 Example:
10099
10100 \snippet code/src_corelib_text_qstring.cpp 7
10101*/
10102QString QString::toHtmlEscaped() const
10103{
10104 const auto pos = std::u16string_view(*this).find_first_of(u"<>&\"");
10105 if (pos == std::u16string_view::npos)
10106 return *this;
10107 QString rich;
10108 rich.reserve(qsizetype(size() * 1.1)); // cannot overflow (sizeof(value_type) == 2)!
10109 rich += qToStringViewIgnoringNull(*this).first(pos);
10110 for (auto ch : qToStringViewIgnoringNull(*this).sliced(pos)) {
10111 if (ch == u'<')
10112 rich += "&lt;"_L1;
10113 else if (ch == u'>')
10114 rich += "&gt;"_L1;
10115 else if (ch == u'&')
10116 rich += "&amp;"_L1;
10117 else if (ch == u'"')
10118 rich += "&quot;"_L1;
10119 else
10120 rich += ch;
10121 }
10122 rich.squeeze();
10123 return rich;
10124}
10125
10126/*!
10127 \macro QStringLiteral(str)
10128 \relates QString
10129
10130 The macro generates the data for a QString out of the string literal \a str
10131 at compile time. Creating a QString from it is free in this case, and the
10132 generated string data is stored in the read-only segment of the compiled
10133 object file.
10134
10135 If you have code that looks like this:
10136
10137 \snippet code/src_corelib_text_qstring.cpp 9
10138
10139 then a temporary QString will be created to be passed as the \c{hasAttribute}
10140 function parameter. This can be quite expensive, as it involves a memory
10141 allocation and the copy/conversion of the data into QString's internal
10142 encoding.
10143
10144 This cost can be avoided by using QStringLiteral instead:
10145
10146 \snippet code/src_corelib_text_qstring.cpp 10
10147
10148 In this case, QString's internal data will be generated at compile time; no
10149 conversion or allocation will occur at runtime.
10150
10151 Using QStringLiteral instead of a double quoted plain C++ string literal can
10152 significantly speed up creation of QString instances from data known at
10153 compile time.
10154
10155 \note QLatin1StringView can still be more efficient than QStringLiteral
10156 when the string is passed to a function that has an overload taking
10157 QLatin1StringView and this overload avoids conversion to QString. For
10158 instance, QString::operator==() can compare to a QLatin1StringView
10159 directly:
10160
10161 \snippet code/src_corelib_text_qstring.cpp 11
10162
10163 \note Some compilers have bugs encoding strings containing characters outside
10164 the US-ASCII character set. Make sure you prefix your string with \c{u} in
10165 those cases. It is optional otherwise.
10166
10167 \note QStringLiteral is interchangeable with \l operator""_s. The latter saves
10168 typing when many string literals are present in the code.
10169
10170 \sa QByteArrayLiteral
10171*/
10172
10173#if QT_DEPRECATED_SINCE(6, 8)
10174/*!
10175 \fn QtLiterals::operator""_qs(const char16_t *str, size_t size)
10176
10177 \relates QString
10178 \since 6.2
10179 \deprecated [6.8] Use \c _s from Qt::StringLiterals namespace instead.
10180
10181 Literal operator that creates a QString out of the first \a size characters in
10182 the char16_t string literal \a str.
10183
10184 The QString is created at compile time, and the generated string data is stored
10185 in the read-only segment of the compiled object file. Duplicate literals may
10186 share the same read-only memory. This functionality is interchangeable with
10187 QStringLiteral, but saves typing when many string literals are present in the
10188 code.
10189
10190 The following code creates a QString:
10191 \code
10192 auto str = u"hello"_qs;
10193 \endcode
10194
10195 \sa QStringLiteral, QtLiterals::operator""_qba(const char *str, size_t size)
10196*/
10197#endif // QT_DEPRECATED_SINCE(6, 8)
10198
10199/*!
10200 \fn Qt::Literals::StringLiterals::operator""_s(const char16_t *str, size_t size)
10201
10202 \relates QString
10203 \since 6.4
10204
10205 Literal operator that creates a QString out of the first \a size characters in
10206 the char16_t string literal \a str.
10207
10208 The QString is created at compile time, and the generated string data is stored
10209 in the read-only segment of the compiled object file. Duplicate literals may
10210 share the same read-only memory. This functionality is interchangeable with
10211 QStringLiteral, but saves typing when many string literals are present in the
10212 code.
10213
10214 The following code creates a QString:
10215 \code
10216 using namespace Qt::StringLiterals;
10217
10218 auto str = u"hello"_s;
10219 \endcode
10220
10221 \sa Qt::Literals::StringLiterals
10222*/
10223
10224/*!
10225 \internal
10226 */
10227void QAbstractConcatenable::appendLatin1To(QLatin1StringView in, QChar *out) noexcept
10228{
10229 qt_from_latin1(reinterpret_cast<char16_t *>(out), in.data(), size_t(in.size()));
10230}
10231
10232/*!
10233 \fn template <typename T> qsizetype erase(QString &s, const T &t)
10234 \relates QString
10235 \since 6.1
10236
10237 Removes all elements that compare equal to \a t from the
10238 string \a s. Returns the number of elements removed, if any.
10239
10240 \sa erase_if
10241*/
10242
10243/*!
10244 \fn template <typename Predicate> qsizetype erase_if(QString &s, Predicate pred)
10245 \relates QString
10246 \since 6.1
10247
10248 Removes all elements for which the predicate \a pred returns true
10249 from the string \a s. Returns the number of elements removed, if
10250 any.
10251
10252 \sa erase
10253*/
10254
10255/*!
10256 \macro const char *qPrintable(const QString &str)
10257 \relates QString
10258
10259 Returns \a str as a \c{const char *}. This is equivalent to
10260 \a{str}.toLocal8Bit().\l{QByteArray::}{constData()}.
10261
10262 The char pointer will be invalid after the statement in which
10263 qPrintable() is used. This is because the array returned by
10264 QString::toLocal8Bit() will fall out of scope.
10265
10266 \note qDebug(), qInfo(), qWarning(), qCritical(), qFatal() expect
10267 %s arguments to be UTF-8 encoded, while qPrintable() converts to
10268 local 8-bit encoding. Therefore qUtf8Printable() should be used
10269 for logging strings instead of qPrintable().
10270
10271 \sa qUtf8Printable()
10272*/
10273
10274/*!
10275 \macro const char *qUtf8Printable(const QString &str)
10276 \relates QString
10277 \since 5.4
10278
10279 Returns \a str as a \c{const char *}. This is equivalent to
10280 \a{str}.toUtf8().\l{QByteArray::}{constData()}.
10281
10282 The char pointer will be invalid after the statement in which
10283 qUtf8Printable() is used. This is because the array returned by
10284 QString::toUtf8() will fall out of scope.
10285
10286 Example:
10287
10288 \snippet code/src_corelib_text_qstring.cpp qUtf8Printable
10289
10290 \sa qPrintable(), qDebug(), qInfo(), qWarning(), qCritical(), qFatal()
10291*/
10292
10293/*!
10294 \macro const wchar_t *qUtf16Printable(const QString &str)
10295 \relates QString
10296 \since 5.7
10297
10298 Returns \a str as a \c{const ushort *}, but cast to a \c{const wchar_t *}
10299 to avoid warnings. This is equivalent to \a{str}.utf16() plus some casting.
10300
10301 The only useful thing you can do with the return value of this macro is to
10302 pass it to QString::asprintf() for use in a \c{%ls} conversion. In particular,
10303 the return value is \e{not} a valid \c{const wchar_t*}!
10304
10305 In general, the pointer will be invalid after the statement in which
10306 qUtf16Printable() is used. This is because the pointer may have been
10307 obtained from a temporary expression, which will fall out of scope.
10308
10309 Example:
10310
10311 \snippet code/src_corelib_text_qstring.cpp qUtf16Printable
10312
10313 \sa qPrintable(), qDebug(), qInfo(), qWarning(), qCritical(), qFatal()
10314*/
10315
10316QT_END_NAMESPACE
10317
10318#undef REHASH
QString convertToQString(QAnyStringView string)
Definition qstring.cpp:5560
Definition qlist.h:82
char32_t next(char32_t invalidAs=QChar::ReplacementCharacter)
bool hasNext() const
\inmodule QtCore
QList< uint > convertToUcs4(QStringView string)
Definition qstring.cpp:5816
QByteArray convertToUtf8(QStringView string)
Definition qstring.cpp:5761
QByteArray convertToLocal8Bit(QStringView string)
Definition qstring.cpp:5718
QByteArray convertToLatin1(QStringView string)
Definition qstring.cpp:5577
Combined button and popup list for selecting options.
static QString convertCase(T &str, QUnicodeTables::Case which)
Definition qstring.cpp:7176
static constexpr NormalizationCorrection uc_normalization_corrections[]
Q_CORE_EXPORT Q_DECL_PURE_FUNCTION bool startsWith(QStringView haystack, QStringView needle, Qt::CaseSensitivity cs=Qt::CaseSensitive) noexcept
Definition qstring.cpp:9743
Q_CORE_EXPORT Q_DECL_PURE_FUNCTION bool endsWith(QStringView haystack, QStringView needle, Qt::CaseSensitivity cs=Qt::CaseSensitive) noexcept
Definition qstring.cpp:9783
Q_CORE_EXPORT Q_DECL_PURE_FUNCTION bool isLower(QStringView s) noexcept
Definition qstring.cpp:5497
const QString & asString(const QString &s)
Definition qstring.h:1713
Q_CORE_EXPORT Q_DECL_PURE_FUNCTION bool isValidUtf16(QStringView s) noexcept
Definition qstring.cpp:906
Q_CORE_EXPORT Q_DECL_PURE_FUNCTION bool equalStrings(QStringView lhs, QStringView rhs) noexcept
Definition qstring.cpp:1374
qsizetype findString(QStringView str, qsizetype from, QChar needle, Qt::CaseSensitivity cs=Qt::CaseSensitive) noexcept
Q_CORE_EXPORT Q_DECL_PURE_FUNCTION bool isRightToLeft(QStringView string) noexcept
Q_CORE_EXPORT Q_DECL_PURE_FUNCTION int compareStrings(QStringView lhs, QStringView rhs, Qt::CaseSensitivity cs=Qt::CaseSensitive) noexcept
Q_CORE_EXPORT Q_DECL_PURE_FUNCTION bool isAscii(QLatin1StringView s) noexcept
Definition qstring.cpp:851
constexpr bool isLatin1(QLatin1StringView s) noexcept
Definition qstring.h:77
Q_CORE_EXPORT Q_DECL_PURE_FUNCTION const char16_t * qustrcasechr(QStringView str, char16_t ch) noexcept
Definition qstring.cpp:776
Q_CORE_EXPORT Q_DECL_PURE_FUNCTION bool isUpper(QStringView s) noexcept
Definition qstring.cpp:5502
Q_CORE_EXPORT Q_DECL_PURE_FUNCTION const char16_t * qustrchr(QStringView str, char16_t ch) noexcept
Definition qstring.cpp:688
void qt_to_latin1_unchecked(uchar *dst, const char16_t *uc, qsizetype len)
Definition qstring.cpp:1189
static char16_t foldCase(char16_t ch) noexcept
Definition qchar.cpp:1696
#define __has_feature(x)
uint QT_FASTCALL fetch1Pixel< QPixelLayout::BPP1LSB >(const uchar *src, int index)
bool comparesEqual(const QFileInfo &lhs, const QFileInfo &rhs)
static bool isAscii_helper(const char16_t *&ptr, const char16_t *end)
Definition qstring.cpp:859
static Int toIntegral(QStringView string, bool *ok, int base)
Definition qstring.cpp:7666
void qt_to_latin1(uchar *dst, const char16_t *src, qsizetype length)
Definition qstring.cpp:1184
Qt::strong_ordering compareThreeWay(const QByteArray &lhs, const QChar &rhs) noexcept
Definition qstring.cpp:6752
static void append_utf8(QString &qs, const char *cs, qsizetype len)
Definition qstring.cpp:7299
#define ATTRIBUTE_NO_SANITIZE
Definition qstring.cpp:367
bool qt_is_ascii(const char *&ptr, const char *end) noexcept
Definition qstring.cpp:787
static bool checkCase(QStringView s, QUnicodeTables::Case c) noexcept
Definition qstring.cpp:5486
static void replace_helper(QString &str, QSpan< qsizetype > indices, qsizetype blen, QStringView after)
Definition qstring.cpp:3687
Q_CORE_EXPORT void qt_from_latin1(char16_t *dst, const char *str, size_t size) noexcept
Definition qstring.cpp:921
static int ucstrcmp(const char16_t *a, size_t alen, const Char2 *b, size_t blen)
Definition qstring.cpp:1347
bool comparesEqual(const QByteArray &lhs, char16_t rhs) noexcept
Definition qstring.cpp:6758
Q_DECLARE_TYPEINFO(Part, Q_PRIMITIVE_TYPE)
static void removeStringImpl(QString &s, const T &needle, Qt::CaseSensitivity cs)
Definition qstring.cpp:3496
static bool needsReallocate(const QString &str, qsizetype newSize)
Definition qstring.cpp:2638
static int qArgDigitValue(QChar ch) noexcept
Definition qstring.cpp:1614
bool comparesEqual(const QByteArray &lhs, const QChar &rhs) noexcept
Definition qstring.cpp:6747
#define REHASH(a)
Definition qstring.cpp:66
bool comparesEqual(const QByteArrayView &lhs, char16_t rhs) noexcept
Definition qstring.cpp:6736
static int ucstrncmp(const char16_t *a, const char16_t *b, size_t l)
Definition qstring.cpp:1265
static Q_NEVER_INLINE int ucstricmp(qsizetype alen, const char16_t *a, qsizetype blen, const char *b)
Definition qstring.cpp:1220
static QByteArray qt_convert_to_latin1(QStringView string)
Definition qstring.cpp:5583
static bool ucstreq(const char16_t *a, size_t alen, const Char2 *b)
Definition qstring.cpp:1340
static QList< uint > qt_convert_to_ucs4(QStringView string)
Definition qstring.cpp:5788
qsizetype qFindStringBoyerMoore(QStringView haystack, qsizetype from, QStringView needle, Qt::CaseSensitivity cs)
static QByteArray qt_convert_to_local_8bit(QStringView string)
Definition qstring.cpp:5695
static LengthMod parse_length_modifier(const char *&c) noexcept
Definition qstring.cpp:7355
static ArgEscapeData findArgEscapes(QStringView s)
Definition qstring.cpp:8580
static QByteArray qt_convert_to_utf8(QStringView str)
Definition qstring.cpp:5741
static void qt_to_latin1_internal(uchar *dst, const char16_t *src, qsizetype length)
Definition qstring.cpp:1005
QtPrivate::QCaseInsensitiveLatin1Hash CaseInsensitiveL1
Definition qstring.cpp:1354
LengthMod
Definition qstring.cpp:7344
@ lm_z
Definition qstring.cpp:7344
@ lm_none
Definition qstring.cpp:7344
@ lm_t
Definition qstring.cpp:7344
@ lm_l
Definition qstring.cpp:7344
@ lm_ll
Definition qstring.cpp:7344
@ lm_hh
Definition qstring.cpp:7344
@ lm_L
Definition qstring.cpp:7344
@ lm_h
Definition qstring.cpp:7344
@ lm_j
Definition qstring.cpp:7344
static void insert_helper(QString &str, qsizetype i, const T &toInsert)
Definition qstring.cpp:2971
static int latin1nicmp(const char *lhsChar, qsizetype lSize, const char *rhsChar, qsizetype rSize)
Definition qstring.cpp:1356
Qt::strong_ordering compareThreeWay(const QByteArrayView &lhs, const QChar &rhs) noexcept
Definition qstring.cpp:6730
static char16_t to_unicode(const char c)
Definition qstring.cpp:8985
Qt::strong_ordering compareThreeWay(const QByteArray &lhs, char16_t rhs) noexcept
Definition qstring.cpp:6763
static QString replaceArgEscapes(QStringView s, const ArgEscapeData &d, qsizetype field_width, QStringView arg, QStringView larg, QChar fillChar)
Definition qstring.cpp:8656
static QVarLengthArray< char16_t > qt_from_latin1_to_qvla(QLatin1StringView str)
Definition qstring.cpp:996
static Q_NEVER_INLINE int ucstricmp8(const char *utf8, const char *utf8end, const QChar *utf16, const QChar *utf16end)
Definition qstring.cpp:1238
void qt_string_normalize(QString *data, QString::NormalizationForm mode, QChar::UnicodeVersion version, qsizetype from)
Definition qstring.cpp:8443
static uint parse_flag_characters(const char *&c) noexcept
Definition qstring.cpp:7307
static Q_NEVER_INLINE int ucstricmp(qsizetype alen, const char16_t *a, qsizetype blen, const char16_t *b)
Definition qstring.cpp:1195
static char16_t to_unicode(const QChar c)
Definition qstring.cpp:8984
QDataStream & operator>>(QDataStream &in, QString &str)
Definition qstring.cpp:9517
static int getEscape(const Char *uc, qsizetype *pos, qsizetype len)
Definition qstring.cpp:8988
static int ucstrncmp(const char16_t *a, const char *b, size_t l)
Definition qstring.cpp:1318
static bool can_consume(const char *&c, char ch) noexcept
Definition qstring.cpp:7346
static int parse_field_width(const char *&c, qsizetype size)
Definition qstring.cpp:7327
Qt::strong_ordering compareThreeWay(const QByteArrayView &lhs, char16_t rhs) noexcept
Definition qstring.cpp:6741
#define qUtf16Printable(string)
Definition qstring.h:1730
qsizetype occurrences
Definition qstring.cpp:8574
qsizetype escape_len
Definition qstring.cpp:8577
qsizetype locale_occurrences
Definition qstring.cpp:8575
\inmodule QtCore \reentrant
Definition qchar.h:18
constexpr char16_t unicode() const noexcept
Converts a Latin-1 character to an 16-bit-encoded Unicode representation of the character.
Definition qchar.h:22
constexpr QLatin1Char(char c) noexcept
Constructs a Latin-1 character for c.
Definition qchar.h:20
@ BlankBeforePositive
Definition qlocale_p.h:275
@ AddTrailingZeroes
Definition qlocale_p.h:272
static int difference(char lhs, char rhs)