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