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