OpenShot Library | OpenShotAudio 0.2.2
juce_String.h
1
2/** @weakgroup juce_core-text
3 * @{
4 */
5/*
6 ==============================================================================
7
8 This file is part of the JUCE library.
9 Copyright (c) 2017 - ROLI Ltd.
10
11 JUCE is an open source library subject to commercial or open-source
12 licensing.
13
14 The code included in this file is provided under the terms of the ISC license
15 http://www.isc.org/downloads/software-support-policy/isc-license. Permission
16 To use, copy, modify, and/or distribute this software for any purpose with or
17 without fee is hereby granted provided that the above copyright notice and
18 this permission notice appear in all copies.
19
20 JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
21 EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
22 DISCLAIMED.
23
24 ==============================================================================
25*/
26
27namespace juce
28{
29
30//==============================================================================
31/**
32 The JUCE String class!
33
34 Using a reference-counted internal representation, these strings are fast
35 and efficient, and there are methods to do just about any operation you'll ever
36 dream of.
37
38 @see StringArray, StringPairArray
39
40 @tags{Core}
41*/
42class JUCE_API String final
43{
44public:
45 //==============================================================================
46 /** Creates an empty string.
47 @see empty
48 */
49 String() noexcept;
50
51 /** Creates a copy of another string. */
52 String (const String&) noexcept;
53
54 /** Move constructor */
55 String (String&&) noexcept;
56
57 /** Creates a string from a zero-terminated ascii text string.
58
59 The string passed-in must not contain any characters with a value above 127, because
60 these can't be converted to unicode without knowing the original encoding that was
61 used to create the string. If you attempt to pass-in values above 127, you'll get an
62 assertion.
63
64 To create strings with extended characters from UTF-8, you should explicitly call
65 String (CharPointer_UTF8 ("my utf8 string..")). It's *highly* recommended that you
66 use UTF-8 with escape characters in your source code to represent extended characters,
67 because there's no other way to represent unicode strings in a way that isn't dependent
68 on the compiler, source code editor and platform.
69 */
70 String (const char* text);
71
72 /** Creates a string from a string of 8-bit ascii characters.
73
74 The string passed-in must not contain any characters with a value above 127, because
75 these can't be converted to unicode without knowing the original encoding that was
76 used to create the string. If you attempt to pass-in values above 127, you'll get an
77 assertion.
78
79 To create strings with extended characters from UTF-8, you should explicitly call
80 String (CharPointer_UTF8 ("my utf8 string..")). It's *highly* recommended that you
81 use UTF-8 with escape characters in your source code to represent extended characters,
82 because there's no other way to represent unicode strings in a way that isn't dependent
83 on the compiler, source code editor and platform.
84
85 This will use up to the first maxChars characters of the string (or less if the string
86 is actually shorter).
87 */
88 String (const char* text, size_t maxChars);
89
90 /** Creates a string from a wchar_t character string.
91 Depending on the platform, this may be treated as either UTF-32 or UTF-16.
92 */
93 String (const wchar_t* text);
94
95 /** Creates a string from a wchar_t character string.
96 Depending on the platform, this may be treated as either UTF-32 or UTF-16.
97 */
98 String (const wchar_t* text, size_t maxChars);
99
100 //==============================================================================
101 /** Creates a string from a UTF-8 character string */
103
104 /** Creates a string from a UTF-8 character string */
105 String (CharPointer_UTF8 text, size_t maxChars);
106
107 /** Creates a string from a UTF-8 character string */
109
110 //==============================================================================
111 /** Creates a string from a UTF-16 character string */
113
114 /** Creates a string from a UTF-16 character string */
115 String (CharPointer_UTF16 text, size_t maxChars);
116
117 /** Creates a string from a UTF-16 character string */
119
120 //==============================================================================
121 /** Creates a string from a UTF-32 character string */
123
124 /** Creates a string from a UTF-32 character string */
125 String (CharPointer_UTF32 text, size_t maxChars);
126
127 /** Creates a string from a UTF-32 character string */
129
130 //==============================================================================
131 /** Creates a string from an ASCII character string */
133
134 /** Creates a string from a UTF-8 encoded std::string. */
135 String (const std::string&);
136
137 /** Creates a string from a StringRef */
139
140 //==============================================================================
141 /** Creates a string from a single character. */
142 static String charToString (juce_wchar character);
143
144 /** Destructor. */
145 ~String() noexcept;
146
147 /** This is the character encoding type used internally to store the string.
148
149 By setting the value of JUCE_STRING_UTF_TYPE to 8, 16, or 32, you can change the
150 internal storage format of the String class. UTF-8 uses the least space (if your strings
151 contain few extended characters), but call operator[] involves iterating the string to find
152 the required index. UTF-32 provides instant random access to its characters, but uses 4 bytes
153 per character to store them. UTF-16 uses more space than UTF-8 and is also slow to index,
154 but is the native wchar_t format used in Windows.
155
156 It doesn't matter too much which format you pick, because the toUTF8(), toUTF16() and
157 toUTF32() methods let you access the string's content in any of the other formats.
158 */
159 #if (JUCE_STRING_UTF_TYPE == 32)
161 #elif (JUCE_STRING_UTF_TYPE == 16)
163 #elif (DOXYGEN || JUCE_STRING_UTF_TYPE == 8)
165 #else
166 #error "You must set the value of JUCE_STRING_UTF_TYPE to be either 8, 16, or 32!"
167 #endif
168
169 //==============================================================================
170 /** Generates a probably-unique 32-bit hashcode from this string. */
171 int hashCode() const noexcept;
172
173 /** Generates a probably-unique 64-bit hashcode from this string. */
174 int64 hashCode64() const noexcept;
175
176 /** Generates a probably-unique hashcode from this string. */
177 size_t hash() const noexcept;
178
179 /** Returns the number of characters in the string. */
180 int length() const noexcept;
181
182 //==============================================================================
183 // Assignment and concatenation operators..
184
185 /** Replaces this string's contents with another string. */
186 String& operator= (const String& other) noexcept;
187
188 /** Moves the contents of another string to the receiver */
189 String& operator= (String&& other) noexcept;
190
191 /** Appends another string at the end of this one. */
192 String& operator+= (const String& stringToAppend);
193 /** Appends another string at the end of this one. */
194 String& operator+= (const char* textToAppend);
195 /** Appends another string at the end of this one. */
196 String& operator+= (const wchar_t* textToAppend);
197 /** Appends another string at the end of this one. */
198 String& operator+= (StringRef textToAppend);
199 /** Appends a decimal number at the end of this string. */
200 String& operator+= (int numberToAppend);
201 /** Appends a decimal number at the end of this string. */
202 String& operator+= (long numberToAppend);
203 /** Appends a decimal number at the end of this string. */
204 String& operator+= (int64 numberToAppend);
205 /** Appends a decimal number at the end of this string. */
206 String& operator+= (uint64 numberToAppend);
207 /** Appends a character at the end of this string. */
208 String& operator+= (char characterToAppend);
209 /** Appends a character at the end of this string. */
210 String& operator+= (wchar_t characterToAppend);
211 #if ! JUCE_NATIVE_WCHAR_IS_UTF32
212 /** Appends a character at the end of this string. */
213 String& operator+= (juce_wchar characterToAppend);
214 #endif
215
216 /** Appends a string to the end of this one.
217
218 @param textToAppend the string to add
219 @param maxCharsToTake the maximum number of characters to take from the string passed in
220 */
221 void append (const String& textToAppend, size_t maxCharsToTake);
222
223 /** Appends a string to the end of this one.
224
225 @param startOfTextToAppend the start of the string to add. This must not be a nullptr
226 @param endOfTextToAppend the end of the string to add. This must not be a nullptr
227 */
228 void appendCharPointer (CharPointerType startOfTextToAppend,
229 CharPointerType endOfTextToAppend);
230
231 /** Appends a string to the end of this one.
232
233 @param startOfTextToAppend the start of the string to add. This must not be a nullptr
234 @param endOfTextToAppend the end of the string to add. This must not be a nullptr
235 */
236 template <class CharPointer>
237 void appendCharPointer (CharPointer startOfTextToAppend,
238 CharPointer endOfTextToAppend)
239 {
240 jassert (startOfTextToAppend.getAddress() != nullptr && endOfTextToAppend.getAddress() != nullptr);
241
242 size_t extraBytesNeeded = 0, numChars = 1;
243
244 for (auto t = startOfTextToAppend; t != endOfTextToAppend && ! t.isEmpty(); ++numChars)
245 extraBytesNeeded += CharPointerType::getBytesRequiredFor (t.getAndAdvance());
246
247 if (extraBytesNeeded > 0)
248 {
249 auto byteOffsetOfNull = getByteOffsetOfEnd();
250
251 preallocateBytes (byteOffsetOfNull + extraBytesNeeded);
252 CharPointerType (addBytesToPointer (text.getAddress(), (int) byteOffsetOfNull))
253 .writeWithCharLimit (startOfTextToAppend, (int) numChars);
254 }
255 }
256
257 /** Appends a string to the end of this one. */
258 void appendCharPointer (CharPointerType textToAppend);
259
260 /** Appends a string to the end of this one.
261
262 @param textToAppend the string to add
263 @param maxCharsToTake the maximum number of characters to take from the string passed in
264 */
265 template <class CharPointer>
266 void appendCharPointer (CharPointer textToAppend, size_t maxCharsToTake)
267 {
268 if (textToAppend.getAddress() != nullptr)
269 {
270 size_t extraBytesNeeded = 0, numChars = 1;
271
272 for (auto t = textToAppend; numChars <= maxCharsToTake && ! t.isEmpty(); ++numChars)
273 extraBytesNeeded += CharPointerType::getBytesRequiredFor (t.getAndAdvance());
274
275 if (extraBytesNeeded > 0)
276 {
277 auto byteOffsetOfNull = getByteOffsetOfEnd();
278
279 preallocateBytes (byteOffsetOfNull + extraBytesNeeded);
280 CharPointerType (addBytesToPointer (text.getAddress(), (int) byteOffsetOfNull))
281 .writeWithCharLimit (textToAppend, (int) numChars);
282 }
283 }
284 }
285
286 /** Appends a string to the end of this one. */
287 template <class CharPointer>
288 void appendCharPointer (CharPointer textToAppend)
289 {
290 appendCharPointer (textToAppend, std::numeric_limits<size_t>::max());
291 }
292
293 //==============================================================================
294 // Comparison methods..
295
296 /** Returns true if the string contains no characters.
297 Note that there's also an isNotEmpty() method to help write readable code.
298 @see containsNonWhitespaceChars()
299 */
300 inline bool isEmpty() const noexcept { return text.isEmpty(); }
301
302 /** Returns true if the string contains at least one character.
303 Note that there's also an isEmpty() method to help write readable code.
304 @see containsNonWhitespaceChars()
305 */
306 inline bool isNotEmpty() const noexcept { return ! text.isEmpty(); }
307
308 /** Resets this string to be empty. */
309 void clear() noexcept;
310
311 /** Case-insensitive comparison with another string. */
312 bool equalsIgnoreCase (const String& other) const noexcept;
313
314 /** Case-insensitive comparison with another string. */
315 bool equalsIgnoreCase (StringRef other) const noexcept;
316
317 /** Case-insensitive comparison with another string. */
318 bool equalsIgnoreCase (const wchar_t* other) const noexcept;
319
320 /** Case-insensitive comparison with another string. */
321 bool equalsIgnoreCase (const char* other) const noexcept;
322
323 /** Case-sensitive comparison with another string.
324 @returns 0 if the two strings are identical; negative if this string comes before
325 the other one alphabetically, or positive if it comes after it.
326 */
327 int compare (const String& other) const noexcept;
328
329 /** Case-sensitive comparison with another string.
330 @returns 0 if the two strings are identical; negative if this string comes before
331 the other one alphabetically, or positive if it comes after it.
332 */
333 int compare (const char* other) const noexcept;
334
335 /** Case-sensitive comparison with another string.
336 @returns 0 if the two strings are identical; negative if this string comes before
337 the other one alphabetically, or positive if it comes after it.
338 */
339 int compare (const wchar_t* other) const noexcept;
340
341 /** Case-insensitive comparison with another string.
342 @returns 0 if the two strings are identical; negative if this string comes before
343 the other one alphabetically, or positive if it comes after it.
344 */
345 int compareIgnoreCase (const String& other) const noexcept;
346
347 /** Compares two strings, taking into account textual characteristics like numbers and spaces.
348
349 This comparison is case-insensitive and can detect words and embedded numbers in the
350 strings, making it good for sorting human-readable lists of things like filenames.
351
352 @returns 0 if the two strings are identical; negative if this string comes before
353 the other one alphabetically, or positive if it comes after it.
354 */
355 int compareNatural (StringRef other, bool isCaseSensitive = false) const noexcept;
356
357 /** Tests whether the string begins with another string.
358 If the parameter is an empty string, this will always return true.
359 Uses a case-sensitive comparison.
360 */
361 bool startsWith (StringRef text) const noexcept;
362
363 /** Tests whether the string begins with a particular character.
364 If the character is 0, this will always return false.
365 Uses a case-sensitive comparison.
366 */
367 bool startsWithChar (juce_wchar character) const noexcept;
368
369 /** Tests whether the string begins with another string.
370 If the parameter is an empty string, this will always return true.
371 Uses a case-insensitive comparison.
372 */
373 bool startsWithIgnoreCase (StringRef text) const noexcept;
374
375 /** Tests whether the string ends with another string.
376 If the parameter is an empty string, this will always return true.
377 Uses a case-sensitive comparison.
378 */
379 bool endsWith (StringRef text) const noexcept;
380
381 /** Tests whether the string ends with a particular character.
382 If the character is 0, this will always return false.
383 Uses a case-sensitive comparison.
384 */
385 bool endsWithChar (juce_wchar character) const noexcept;
386
387 /** Tests whether the string ends with another string.
388 If the parameter is an empty string, this will always return true.
389 Uses a case-insensitive comparison.
390 */
391 bool endsWithIgnoreCase (StringRef text) const noexcept;
392
393 /** Tests whether the string contains another substring.
394 If the parameter is an empty string, this will always return true.
395 Uses a case-sensitive comparison.
396 */
397 bool contains (StringRef text) const noexcept;
398
399 /** Tests whether the string contains a particular character.
400 Uses a case-sensitive comparison.
401 */
402 bool containsChar (juce_wchar character) const noexcept;
403
404 /** Tests whether the string contains another substring.
405 Uses a case-insensitive comparison.
406 */
407 bool containsIgnoreCase (StringRef text) const noexcept;
408
409 /** Tests whether the string contains another substring as a distinct word.
410
411 @returns true if the string contains this word, surrounded by
412 non-alphanumeric characters
413 @see indexOfWholeWord, containsWholeWordIgnoreCase
414 */
415 bool containsWholeWord (StringRef wordToLookFor) const noexcept;
416
417 /** Tests whether the string contains another substring as a distinct word.
418
419 @returns true if the string contains this word, surrounded by
420 non-alphanumeric characters
421 @see indexOfWholeWordIgnoreCase, containsWholeWord
422 */
423 bool containsWholeWordIgnoreCase (StringRef wordToLookFor) const noexcept;
424
425 /** Finds an instance of another substring if it exists as a distinct word.
426
427 @returns if the string contains this word, surrounded by non-alphanumeric characters,
428 then this will return the index of the start of the substring. If it isn't
429 found, then it will return -1
430 @see indexOfWholeWordIgnoreCase, containsWholeWord
431 */
432 int indexOfWholeWord (StringRef wordToLookFor) const noexcept;
433
434 /** Finds an instance of another substring if it exists as a distinct word.
435
436 @returns if the string contains this word, surrounded by non-alphanumeric characters,
437 then this will return the index of the start of the substring. If it isn't
438 found, then it will return -1
439 @see indexOfWholeWord, containsWholeWordIgnoreCase
440 */
441 int indexOfWholeWordIgnoreCase (StringRef wordToLookFor) const noexcept;
442
443 /** Looks for any of a set of characters in the string.
444 Uses a case-sensitive comparison.
445
446 @returns true if the string contains any of the characters from
447 the string that is passed in.
448 */
449 bool containsAnyOf (StringRef charactersItMightContain) const noexcept;
450
451 /** Looks for a set of characters in the string.
452 Uses a case-sensitive comparison.
453
454 @returns Returns false if any of the characters in this string do not occur in
455 the parameter string. If this string is empty, the return value will
456 always be true.
457 */
458 bool containsOnly (StringRef charactersItMightContain) const noexcept;
459
460 /** Returns true if this string contains any non-whitespace characters.
461
462 This will return false if the string contains only whitespace characters, or
463 if it's empty.
464
465 It is equivalent to calling "myString.trim().isNotEmpty()".
466 */
467 bool containsNonWhitespaceChars() const noexcept;
468
469 /** Returns true if the string matches this simple wildcard expression.
470
471 So for example String ("abcdef").matchesWildcard ("*DEF", true) would return true.
472
473 This isn't a full-blown regex though! The only wildcard characters supported
474 are "*" and "?". It's mainly intended for filename pattern matching.
475 */
476 bool matchesWildcard (StringRef wildcard, bool ignoreCase) const noexcept;
477
478 //==============================================================================
479 // Substring location methods..
480
481 /** Searches for a character inside this string.
482 Uses a case-sensitive comparison.
483 @returns the index of the first occurrence of the character in this
484 string, or -1 if it's not found.
485 */
486 int indexOfChar (juce_wchar characterToLookFor) const noexcept;
487
488 /** Searches for a character inside this string.
489 Uses a case-sensitive comparison.
490 @param startIndex the index from which the search should proceed
491 @param characterToLookFor the character to look for
492 @returns the index of the first occurrence of the character in this
493 string, or -1 if it's not found.
494 */
495 int indexOfChar (int startIndex, juce_wchar characterToLookFor) const noexcept;
496
497 /** Returns the index of the first character that matches one of the characters
498 passed-in to this method.
499
500 This scans the string, beginning from the startIndex supplied, and if it finds
501 a character that appears in the string charactersToLookFor, it returns its index.
502
503 If none of these characters are found, it returns -1.
504
505 If ignoreCase is true, the comparison will be case-insensitive.
506
507 @see indexOfChar, lastIndexOfAnyOf
508 */
509 int indexOfAnyOf (StringRef charactersToLookFor,
510 int startIndex = 0,
511 bool ignoreCase = false) const noexcept;
512
513 /** Searches for a substring within this string.
514 Uses a case-sensitive comparison.
515 @returns the index of the first occurrence of this substring, or -1 if it's not found.
516 If textToLookFor is an empty string, this will always return 0.
517 */
518 int indexOf (StringRef textToLookFor) const noexcept;
519
520 /** Searches for a substring within this string.
521 Uses a case-sensitive comparison.
522 @param startIndex the index from which the search should proceed
523 @param textToLookFor the string to search for
524 @returns the index of the first occurrence of this substring, or -1 if it's not found.
525 If textToLookFor is an empty string, this will always return -1.
526 */
527 int indexOf (int startIndex, StringRef textToLookFor) const noexcept;
528
529 /** Searches for a substring within this string.
530 Uses a case-insensitive comparison.
531 @returns the index of the first occurrence of this substring, or -1 if it's not found.
532 If textToLookFor is an empty string, this will always return 0.
533 */
534 int indexOfIgnoreCase (StringRef textToLookFor) const noexcept;
535
536 /** Searches for a substring within this string.
537 Uses a case-insensitive comparison.
538 @param startIndex the index from which the search should proceed
539 @param textToLookFor the string to search for
540 @returns the index of the first occurrence of this substring, or -1 if it's not found.
541 If textToLookFor is an empty string, this will always return -1.
542 */
543 int indexOfIgnoreCase (int startIndex, StringRef textToLookFor) const noexcept;
544
545 /** Searches for a character inside this string (working backwards from the end of the string).
546 Uses a case-sensitive comparison.
547 @returns the index of the last occurrence of the character in this string, or -1 if it's not found.
548 */
549 int lastIndexOfChar (juce_wchar character) const noexcept;
550
551 /** Searches for a substring inside this string (working backwards from the end of the string).
552 Uses a case-sensitive comparison.
553 @returns the index of the start of the last occurrence of the substring within this string,
554 or -1 if it's not found. If textToLookFor is an empty string, this will always return -1.
555 */
556 int lastIndexOf (StringRef textToLookFor) const noexcept;
557
558 /** Searches for a substring inside this string (working backwards from the end of the string).
559 Uses a case-insensitive comparison.
560 @returns the index of the start of the last occurrence of the substring within this string, or -1
561 if it's not found. If textToLookFor is an empty string, this will always return -1.
562 */
563 int lastIndexOfIgnoreCase (StringRef textToLookFor) const noexcept;
564
565 /** Returns the index of the last character in this string that matches one of the
566 characters passed-in to this method.
567
568 This scans the string backwards, starting from its end, and if it finds
569 a character that appears in the string charactersToLookFor, it returns its index.
570
571 If none of these characters are found, it returns -1.
572
573 If ignoreCase is true, the comparison will be case-insensitive.
574
575 @see lastIndexOf, indexOfAnyOf
576 */
577 int lastIndexOfAnyOf (StringRef charactersToLookFor,
578 bool ignoreCase = false) const noexcept;
579
580
581 //==============================================================================
582 // Substring extraction and manipulation methods..
583
584 /** Returns the character at this index in the string.
585 In a release build, no checks are made to see if the index is within a valid range, so be
586 careful! In a debug build, the index is checked and an assertion fires if it's out-of-range.
587
588 Also beware that depending on the encoding format that the string is using internally, this
589 method may execute in either O(1) or O(n) time, so be careful when using it in your algorithms.
590 If you're scanning through a string to inspect its characters, you should never use this operator
591 for random access, it's far more efficient to call getCharPointer() to return a pointer, and
592 then to use that to iterate the string.
593 @see getCharPointer
594 */
595 juce_wchar operator[] (int index) const noexcept;
596
597 /** Returns the final character of the string.
598 If the string is empty this will return 0.
599 */
600 juce_wchar getLastCharacter() const noexcept;
601
602 //==============================================================================
603 /** Returns a subsection of the string.
604
605 If the range specified is beyond the limits of the string, as much as
606 possible is returned.
607
608 @param startIndex the index of the start of the substring needed
609 @param endIndex all characters from startIndex up to (but not including)
610 this index are returned
611 @see fromFirstOccurrenceOf, dropLastCharacters, getLastCharacters, upToFirstOccurrenceOf
612 */
613 String substring (int startIndex, int endIndex) const;
614
615 /** Returns a section of the string, starting from a given position.
616
617 @param startIndex the first character to include. If this is beyond the end
618 of the string, an empty string is returned. If it is zero or
619 less, the whole string is returned.
620 @returns the substring from startIndex up to the end of the string
621 @see dropLastCharacters, getLastCharacters, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf
622 */
623 String substring (int startIndex) const;
624
625 /** Returns a version of this string with a number of characters removed
626 from the end.
627
628 @param numberToDrop the number of characters to drop from the end of the
629 string. If this is greater than the length of the string,
630 an empty string will be returned. If zero or less, the
631 original string will be returned.
632 @see substring, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf, getLastCharacter
633 */
634 String dropLastCharacters (int numberToDrop) const;
635
636 /** Returns a number of characters from the end of the string.
637
638 This returns the last numCharacters characters from the end of the string. If the
639 string is shorter than numCharacters, the whole string is returned.
640
641 @see substring, dropLastCharacters, getLastCharacter
642 */
643 String getLastCharacters (int numCharacters) const;
644
645 //==============================================================================
646 /** Returns a section of the string starting from a given substring.
647
648 This will search for the first occurrence of the given substring, and
649 return the section of the string starting from the point where this is
650 found (optionally not including the substring itself).
651
652 e.g. for the string "123456", fromFirstOccurrenceOf ("34", true) would return "3456", and
653 fromFirstOccurrenceOf ("34", false) would return "56".
654
655 If the substring isn't found, the method will return an empty string.
656
657 If ignoreCase is true, the comparison will be case-insensitive.
658
659 @see upToFirstOccurrenceOf, fromLastOccurrenceOf
660 */
661 String fromFirstOccurrenceOf (StringRef substringToStartFrom,
662 bool includeSubStringInResult,
663 bool ignoreCase) const;
664
665 /** Returns a section of the string starting from the last occurrence of a given substring.
666
667 Similar to fromFirstOccurrenceOf(), but using the last occurrence of the substring, and
668 unlike fromFirstOccurrenceOf(), if the substring isn't found, this method will
669 return the whole of the original string.
670
671 @see fromFirstOccurrenceOf, upToLastOccurrenceOf
672 */
673 String fromLastOccurrenceOf (StringRef substringToFind,
674 bool includeSubStringInResult,
675 bool ignoreCase) const;
676
677 /** Returns the start of this string, up to the first occurrence of a substring.
678
679 This will search for the first occurrence of a given substring, and then
680 return a copy of the string, up to the position of this substring,
681 optionally including or excluding the substring itself in the result.
682
683 e.g. for the string "123456", upTo ("34", false) would return "12", and
684 upTo ("34", true) would return "1234".
685
686 If the substring isn't found, this will return the whole of the original string.
687
688 @see upToLastOccurrenceOf, fromFirstOccurrenceOf
689 */
690 String upToFirstOccurrenceOf (StringRef substringToEndWith,
691 bool includeSubStringInResult,
692 bool ignoreCase) const;
693
694 /** Returns the start of this string, up to the last occurrence of a substring.
695
696 Similar to upToFirstOccurrenceOf(), but this finds the last occurrence rather than the first.
697 If the substring isn't found, this will return the whole of the original string.
698
699 @see upToFirstOccurrenceOf, fromFirstOccurrenceOf
700 */
701 String upToLastOccurrenceOf (StringRef substringToFind,
702 bool includeSubStringInResult,
703 bool ignoreCase) const;
704
705 //==============================================================================
706 /** Returns a copy of this string with any whitespace characters removed from the start and end. */
707 String trim() const;
708
709 /** Returns a copy of this string with any whitespace characters removed from the start. */
710 String trimStart() const;
711
712 /** Returns a copy of this string with any whitespace characters removed from the end. */
713 String trimEnd() const;
714
715 /** Returns a copy of this string, having removed a specified set of characters from its start.
716 Characters are removed from the start of the string until it finds one that is not in the
717 specified set, and then it stops.
718 @param charactersToTrim the set of characters to remove.
719 @see trim, trimStart, trimCharactersAtEnd
720 */
721 String trimCharactersAtStart (StringRef charactersToTrim) const;
722
723 /** Returns a copy of this string, having removed a specified set of characters from its end.
724 Characters are removed from the end of the string until it finds one that is not in the
725 specified set, and then it stops.
726 @param charactersToTrim the set of characters to remove.
727 @see trim, trimEnd, trimCharactersAtStart
728 */
729 String trimCharactersAtEnd (StringRef charactersToTrim) const;
730
731 //==============================================================================
732 /** Returns an upper-case version of this string. */
733 String toUpperCase() const;
734
735 /** Returns an lower-case version of this string. */
736 String toLowerCase() const;
737
738 //==============================================================================
739 /** Replaces a sub-section of the string with another string.
740
741 This will return a copy of this string, with a set of characters
742 from startIndex to startIndex + numCharsToReplace removed, and with
743 a new string inserted in their place.
744
745 Note that this is a const method, and won't alter the string itself.
746
747 @param startIndex the first character to remove. If this is beyond the bounds of the string,
748 it will be constrained to a valid range.
749 @param numCharactersToReplace the number of characters to remove. If zero or less, no
750 characters will be taken out.
751 @param stringToInsert the new string to insert at startIndex after the characters have been
752 removed.
753 */
754 String replaceSection (int startIndex,
755 int numCharactersToReplace,
756 StringRef stringToInsert) const;
757
758 /** Replaces all occurrences of a substring with another string.
759
760 Returns a copy of this string, with any occurrences of stringToReplace
761 swapped for stringToInsertInstead.
762
763 Note that this is a const method, and won't alter the string itself.
764 */
765 String replace (StringRef stringToReplace,
766 StringRef stringToInsertInstead,
767 bool ignoreCase = false) const;
768
769 /** Replaces the first occurrence of a substring with another string.
770
771 Returns a copy of this string, with the first occurrence of stringToReplace
772 swapped for stringToInsertInstead.
773
774 Note that this is a const method, and won't alter the string itself.
775 */
776 String replaceFirstOccurrenceOf (StringRef stringToReplace,
777 StringRef stringToInsertInstead,
778 bool ignoreCase = false) const;
779
780 /** Returns a string with all occurrences of a character replaced with a different one. */
781 String replaceCharacter (juce_wchar characterToReplace,
782 juce_wchar characterToInsertInstead) const;
783
784 /** Replaces a set of characters with another set.
785
786 Returns a string in which each character from charactersToReplace has been replaced
787 by the character at the equivalent position in newCharacters (so the two strings
788 passed in must be the same length).
789
790 e.g. replaceCharacters ("abc", "def") replaces 'a' with 'd', 'b' with 'e', etc.
791
792 Note that this is a const method, and won't affect the string itself.
793 */
794 String replaceCharacters (StringRef charactersToReplace,
795 StringRef charactersToInsertInstead) const;
796
797 /** Returns a version of this string that only retains a fixed set of characters.
798
799 This will return a copy of this string, omitting any characters which are not
800 found in the string passed-in.
801
802 e.g. for "1122334455", retainCharacters ("432") would return "223344"
803
804 Note that this is a const method, and won't alter the string itself.
805 */
806 String retainCharacters (StringRef charactersToRetain) const;
807
808 /** Returns a version of this string with a set of characters removed.
809
810 This will return a copy of this string, omitting any characters which are
811 found in the string passed-in.
812
813 e.g. for "1122334455", removeCharacters ("432") would return "1155"
814
815 Note that this is a const method, and won't alter the string itself.
816 */
817 String removeCharacters (StringRef charactersToRemove) const;
818
819 /** Returns a section from the start of the string that only contains a certain set of characters.
820
821 This returns the leftmost section of the string, up to (and not including) the
822 first character that doesn't appear in the string passed in.
823 */
824 String initialSectionContainingOnly (StringRef permittedCharacters) const;
825
826 /** Returns a section from the start of the string that only contains a certain set of characters.
827
828 This returns the leftmost section of the string, up to (and not including) the
829 first character that occurs in the string passed in. (If none of the specified
830 characters are found in the string, the return value will just be the original string).
831 */
832 String initialSectionNotContaining (StringRef charactersToStopAt) const;
833
834 //==============================================================================
835 /** Checks whether the string might be in quotation marks.
836
837 @returns true if the string begins with a quote character (either a double or single quote).
838 It is also true if there is whitespace before the quote, but it doesn't check the end of the string.
839 @see unquoted, quoted
840 */
841 bool isQuotedString() const;
842
843 /** Removes quotation marks from around the string, (if there are any).
844
845 Returns a copy of this string with any quotes removed from its ends. Quotes that aren't
846 at the ends of the string are not affected. If there aren't any quotes, the original string
847 is returned.
848
849 Note that this is a const method, and won't alter the string itself.
850
851 @see isQuotedString, quoted
852 */
853 String unquoted() const;
854
855 /** Adds quotation marks around a string.
856
857 This will return a copy of the string with a quote at the start and end, (but won't
858 add the quote if there's already one there, so it's safe to call this on strings that
859 may already have quotes around them).
860
861 Note that this is a const method, and won't alter the string itself.
862
863 @param quoteCharacter the character to add at the start and end
864 @see isQuotedString, unquoted
865 */
866 String quoted (juce_wchar quoteCharacter = '"') const;
867
868
869 //==============================================================================
870 /** Creates a string which is a version of a string repeated and joined together.
871
872 @param stringToRepeat the string to repeat
873 @param numberOfTimesToRepeat how many times to repeat it
874 */
875 static String repeatedString (StringRef stringToRepeat,
876 int numberOfTimesToRepeat);
877
878 /** Returns a copy of this string with the specified character repeatedly added to its
879 beginning until the total length is at least the minimum length specified.
880 */
881 String paddedLeft (juce_wchar padCharacter, int minimumLength) const;
882
883 /** Returns a copy of this string with the specified character repeatedly added to its
884 end until the total length is at least the minimum length specified.
885 */
886 String paddedRight (juce_wchar padCharacter, int minimumLength) const;
887
888 /** Creates a string from data in an unknown format.
889
890 This looks at some binary data and tries to guess whether it's Unicode
891 or 8-bit characters, then returns a string that represents it correctly.
892
893 Should be able to handle Unicode endianness correctly, by looking at
894 the first two bytes.
895 */
896 static String createStringFromData (const void* data, int size);
897
898 /** Creates a String from a printf-style parameter list.
899
900 I don't like this method. I don't use it myself, and I recommend avoiding it and
901 using the operator<< methods or pretty much anything else instead. It's only provided
902 here because of the popular unrest that was stirred-up when I tried to remove it...
903
904 If you're really determined to use it, at least make sure that you never, ever,
905 pass any String objects to it as parameters. And bear in mind that internally, depending
906 on the platform, it may be using wchar_t or char character types, so that even string
907 literals can't be safely used as parameters if you're writing portable code.
908 */
909 template <typename... Args>
910 static String formatted (const String& formatStr, Args... args) { return formattedRaw (formatStr.toRawUTF8(), args...); }
911
912 //==============================================================================
913 // Numeric conversions..
914
915 /** Creates a string containing this signed 32-bit integer as a decimal number.
916 @see getIntValue, getFloatValue, getDoubleValue, toHexString
917 */
918 explicit String (int decimalInteger);
919
920 /** Creates a string containing this unsigned 32-bit integer as a decimal number.
921 @see getIntValue, getFloatValue, getDoubleValue, toHexString
922 */
923 explicit String (unsigned int decimalInteger);
924
925 /** Creates a string containing this signed 16-bit integer as a decimal number.
926 @see getIntValue, getFloatValue, getDoubleValue, toHexString
927 */
928 explicit String (short decimalInteger);
929
930 /** Creates a string containing this unsigned 16-bit integer as a decimal number.
931 @see getIntValue, getFloatValue, getDoubleValue, toHexString
932 */
933 explicit String (unsigned short decimalInteger);
934
935 /** Creates a string containing this signed 64-bit integer as a decimal number.
936 @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
937 */
938 explicit String (int64 largeIntegerValue);
939
940 /** Creates a string containing this unsigned 64-bit integer as a decimal number.
941 @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
942 */
943 explicit String (uint64 largeIntegerValue);
944
945 /** Creates a string containing this signed long integer as a decimal number.
946 @see getIntValue, getFloatValue, getDoubleValue, toHexString
947 */
948 explicit String (long decimalInteger);
949
950 /** Creates a string containing this unsigned long integer as a decimal number.
951 @see getIntValue, getFloatValue, getDoubleValue, toHexString
952 */
953 explicit String (unsigned long decimalInteger);
954
955 /** Creates a string representing this floating-point number.
956 @param floatValue the value to convert to a string
957 @see getDoubleValue, getIntValue
958 */
959 explicit String (float floatValue);
960
961 /** Creates a string representing this floating-point number.
962 @param doubleValue the value to convert to a string
963 @see getFloatValue, getIntValue
964 */
965 explicit String (double doubleValue);
966
967 /** Creates a string representing this floating-point number.
968 @param floatValue the value to convert to a string
969 @param numberOfDecimalPlaces if this is > 0 the number will be formatted using that many
970 decimal places, adding trailing zeros as required. If 0 or
971 less the number will be formatted using the C++ standard
972 library default format, which uses scientific notation for
973 large and small numbers.
974 @param useScientificNotation if the number should be formatted using scientific notation
975 @see getDoubleValue, getIntValue
976 */
977 String (float floatValue, int numberOfDecimalPlaces, bool useScientificNotation = false);
978
979 /** Creates a string representing this floating-point number.
980 @param doubleValue the value to convert to a string
981 @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
982 decimal places, adding trailing zeros as required, and
983 will not use exponent notation. If 0 or less, it will use
984 exponent notation if necessary.
985 @param useScientificNotation if the number should be formatted using scientific notation
986 @see getFloatValue, getIntValue
987 */
988 String (double doubleValue, int numberOfDecimalPlaces, bool useScientificNotation = false);
989
990 #ifndef DOXYGEN
991 // Automatically creating a String from a bool opens up lots of nasty type conversion edge cases.
992 // If you want a String representation of a bool you can cast the bool to an int first.
993 explicit String (bool) = delete;
994 #endif
995
996 /** Reads the value of the string as a decimal number (up to 32 bits in size).
997
998 @returns the value of the string as a 32 bit signed base-10 integer.
999 @see getTrailingIntValue, getHexValue32, getHexValue64
1000 */
1001 int getIntValue() const noexcept;
1002
1003 /** Reads the value of the string as a decimal number (up to 64 bits in size).
1004 @returns the value of the string as a 64 bit signed base-10 integer.
1005 */
1006 int64 getLargeIntValue() const noexcept;
1007
1008 /** Parses a decimal number from the end of the string.
1009
1010 This will look for a value at the end of the string.
1011 e.g. for "321 xyz654" it will return 654; for "2 3 4" it'll return 4.
1012
1013 Negative numbers are not handled, so "xyz-5" returns 5.
1014
1015 @see getIntValue
1016 */
1017 int getTrailingIntValue() const noexcept;
1018
1019 /** Parses this string as a floating point number.
1020
1021 @returns the value of the string as a 32-bit floating point value.
1022 @see getDoubleValue
1023 */
1024 float getFloatValue() const noexcept;
1025
1026 /** Parses this string as a floating point number.
1027
1028 @returns the value of the string as a 64-bit floating point value.
1029 @see getFloatValue
1030 */
1031 double getDoubleValue() const noexcept;
1032
1033 /** Parses the string as a hexadecimal number.
1034
1035 Non-hexadecimal characters in the string are ignored.
1036
1037 If the string contains too many characters, then the lowest significant
1038 digits are returned, e.g. "ffff12345678" would produce 0x12345678.
1039
1040 @returns a 32-bit number which is the value of the string in hex.
1041 */
1042 int getHexValue32() const noexcept;
1043
1044 /** Parses the string as a hexadecimal number.
1045
1046 Non-hexadecimal characters in the string are ignored.
1047
1048 If the string contains too many characters, then the lowest significant
1049 digits are returned, e.g. "ffff1234567812345678" would produce 0x1234567812345678.
1050
1051 @returns a 64-bit number which is the value of the string in hex.
1052 */
1053 int64 getHexValue64() const noexcept;
1054
1055 /** Returns a string representing this numeric value in hexadecimal. */
1056 template <typename IntegerType>
1057 static String toHexString (IntegerType number) { return createHex (number); }
1058
1059 /** Returns a string containing a hex dump of a block of binary data.
1060
1061 @param data the binary data to use as input
1062 @param size how many bytes of data to use
1063 @param groupSize how many bytes are grouped together before inserting a
1064 space into the output. e.g. group size 0 has no spaces,
1065 group size 1 looks like: "be a1 c2 ff", group size 2 looks
1066 like "bea1 c2ff".
1067 */
1068 static String toHexString (const void* data, int size, int groupSize = 1);
1069
1070 /** Returns a string containing a decimal with a set number of significant figures.
1071
1072 @param number the input number
1073 @param numberOfSignificantFigures the number of significant figures to use
1074 */
1075 template <typename DecimalType>
1076 static String toDecimalStringWithSignificantFigures (DecimalType number, int numberOfSignificantFigures)
1077 {
1078 jassert (numberOfSignificantFigures > 0);
1079
1080 if (number == 0)
1081 {
1082 if (numberOfSignificantFigures > 1)
1083 {
1084 String result ("0.0");
1085
1086 for (int i = 2; i < numberOfSignificantFigures; ++i)
1087 result += "0";
1088
1089 return result;
1090 }
1091
1092 return "0";
1093 }
1094
1095 auto numDigitsBeforePoint = (int) std::ceil (std::log10 (number < 0 ? -number : number));
1096
1097 #if JUCE_PROJUCER_LIVE_BUILD
1098 auto doubleNumber = (double) number;
1099 constexpr int bufferSize = 311;
1100 char buffer[bufferSize];
1101 auto* ptr = &(buffer[0]);
1102 auto* const safeEnd = ptr + (bufferSize - 1);
1103 auto numSigFigsParsed = 0;
1104
1105 auto writeToBuffer = [safeEnd] (char* destination, char data)
1106 {
1107 *destination++ = data;
1108
1109 if (destination == safeEnd)
1110 {
1111 *destination = '\0';
1112 return true;
1113 }
1114
1115 return false;
1116 };
1117
1118 auto truncateOrRound = [numberOfSignificantFigures] (double fractional, int sigFigsParsed)
1119 {
1120 return (sigFigsParsed == numberOfSignificantFigures - 1) ? (int) std::round (fractional)
1121 : (int) fractional;
1122 };
1123
1124 if (doubleNumber < 0)
1125 {
1126 doubleNumber *= -1;
1127 *ptr++ = '-';
1128 }
1129
1130 if (numDigitsBeforePoint > 0)
1131 {
1132 doubleNumber /= std::pow (10.0, numDigitsBeforePoint);
1133
1134 while (numDigitsBeforePoint-- > 0)
1135 {
1136 if (numSigFigsParsed == numberOfSignificantFigures)
1137 {
1138 if (writeToBuffer (ptr++, '0'))
1139 return buffer;
1140
1141 continue;
1142 }
1143
1144 doubleNumber *= 10;
1145 auto digit = truncateOrRound (doubleNumber, numSigFigsParsed);
1146
1147 if (writeToBuffer (ptr++, (char) ('0' + digit)))
1148 return buffer;
1149
1150 ++numSigFigsParsed;
1151 doubleNumber -= digit;
1152 }
1153
1154 if (numSigFigsParsed == numberOfSignificantFigures)
1155 {
1156 *ptr++ = '\0';
1157 return buffer;
1158 }
1159 }
1160 else
1161 {
1162 *ptr++ = '0';
1163 }
1164
1165 if (writeToBuffer (ptr++, '.'))
1166 return buffer;
1167
1168 while (numSigFigsParsed < numberOfSignificantFigures)
1169 {
1170 doubleNumber *= 10;
1171 auto digit = truncateOrRound (doubleNumber, numSigFigsParsed);
1172
1173 if (writeToBuffer (ptr++, (char) ('0' + digit)))
1174 return buffer;
1175
1176 if (numSigFigsParsed != 0 || digit != 0)
1177 ++numSigFigsParsed;
1178
1179 doubleNumber -= digit;
1180 }
1181
1182 *ptr++ = '\0';
1183 return buffer;
1184 #else
1185 auto shift = numberOfSignificantFigures - numDigitsBeforePoint;
1186 auto factor = std::pow (10.0, shift);
1187 auto rounded = std::round (number * factor) / factor;
1188
1189 std::stringstream ss;
1190 ss << std::fixed << std::setprecision (std::max (shift, 0)) << rounded;
1191 return ss.str();
1192 #endif
1193 }
1194
1195 //==============================================================================
1196 /** Returns the character pointer currently being used to store this string.
1197
1198 Because it returns a reference to the string's internal data, the pointer
1199 that is returned must not be stored anywhere, as it can be deleted whenever the
1200 string changes.
1201 */
1202 inline CharPointerType getCharPointer() const noexcept { return text; }
1203
1204 /** Returns a pointer to a UTF-8 version of this string.
1205
1206 Because it returns a reference to the string's internal data, the pointer
1207 that is returned must not be stored anywhere, as it can be deleted whenever the
1208 string changes.
1209
1210 To find out how many bytes you need to store this string as UTF-8, you can call
1211 CharPointer_UTF8::getBytesRequiredFor (myString.getCharPointer())
1212
1213 @see toRawUTF8, getCharPointer, toUTF16, toUTF32
1214 */
1215 CharPointer_UTF8 toUTF8() const;
1216
1217 /** Returns a pointer to a UTF-8 version of this string.
1218
1219 Because it returns a reference to the string's internal data, the pointer
1220 that is returned must not be stored anywhere, as it can be deleted whenever the
1221 string changes.
1222
1223 To find out how many bytes you need to store this string as UTF-8, you can call
1224 CharPointer_UTF8::getBytesRequiredFor (myString.getCharPointer())
1225
1226 @see getCharPointer, toUTF8, toUTF16, toUTF32
1227 */
1228 const char* toRawUTF8() const;
1229
1230 /** Returns a pointer to a UTF-16 version of this string.
1231
1232 Because it returns a reference to the string's internal data, the pointer
1233 that is returned must not be stored anywhere, as it can be deleted whenever the
1234 string changes.
1235
1236 To find out how many bytes you need to store this string as UTF-16, you can call
1237 CharPointer_UTF16::getBytesRequiredFor (myString.getCharPointer())
1238
1239 @see getCharPointer, toUTF8, toUTF32
1240 */
1241 CharPointer_UTF16 toUTF16() const;
1242
1243 /** Returns a pointer to a UTF-32 version of this string.
1244
1245 Because it returns a reference to the string's internal data, the pointer
1246 that is returned must not be stored anywhere, as it can be deleted whenever the
1247 string changes.
1248
1249 @see getCharPointer, toUTF8, toUTF16
1250 */
1251 CharPointer_UTF32 toUTF32() const;
1252
1253 /** Returns a pointer to a wchar_t version of this string.
1254
1255 Because it returns a reference to the string's internal data, the pointer
1256 that is returned must not be stored anywhere, as it can be deleted whenever the
1257 string changes.
1258
1259 Bear in mind that the wchar_t type is different on different platforms, so on
1260 Windows, this will be equivalent to calling toUTF16(), on unix it'll be the same
1261 as calling toUTF32(), etc.
1262
1263 @see getCharPointer, toUTF8, toUTF16, toUTF32
1264 */
1265 const wchar_t* toWideCharPointer() const;
1266
1267 /** */
1268 std::string toStdString() const;
1269
1270 //==============================================================================
1271 /** Creates a String from a UTF-8 encoded buffer.
1272 If the size is < 0, it'll keep reading until it hits a zero.
1273 */
1274 static String fromUTF8 (const char* utf8buffer, int bufferSizeBytes = -1);
1275
1276 /** Returns the number of bytes required to represent this string as UTF8.
1277 The number returned does NOT include the trailing zero.
1278 @see toUTF8, copyToUTF8
1279 */
1280 size_t getNumBytesAsUTF8() const noexcept;
1281
1282 //==============================================================================
1283 /** Copies the string to a buffer as UTF-8 characters.
1284
1285 Returns the number of bytes copied to the buffer, including the terminating null
1286 character.
1287
1288 To find out how many bytes you need to store this string as UTF-8, you can call
1289 CharPointer_UTF8::getBytesRequiredFor (myString.getCharPointer())
1290
1291 @param destBuffer the place to copy it to; if this is a null pointer, the method just
1292 returns the number of bytes required (including the terminating null character).
1293 @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the string won't fit, it'll
1294 put in as many as it can while still allowing for a terminating null char at the
1295 end, and will return the number of bytes that were actually used.
1296 @see CharPointer_UTF8::writeWithDestByteLimit
1297 */
1298 size_t copyToUTF8 (CharPointer_UTF8::CharType* destBuffer, size_t maxBufferSizeBytes) const noexcept;
1299
1300 /** Copies the string to a buffer as UTF-16 characters.
1301
1302 Returns the number of bytes copied to the buffer, including the terminating null
1303 character.
1304
1305 To find out how many bytes you need to store this string as UTF-16, you can call
1306 CharPointer_UTF16::getBytesRequiredFor (myString.getCharPointer())
1307
1308 @param destBuffer the place to copy it to; if this is a null pointer, the method just
1309 returns the number of bytes required (including the terminating null character).
1310 @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the string won't fit, it'll
1311 put in as many as it can while still allowing for a terminating null char at the
1312 end, and will return the number of bytes that were actually used.
1313 @see CharPointer_UTF16::writeWithDestByteLimit
1314 */
1315 size_t copyToUTF16 (CharPointer_UTF16::CharType* destBuffer, size_t maxBufferSizeBytes) const noexcept;
1316
1317 /** Copies the string to a buffer as UTF-32 characters.
1318
1319 Returns the number of bytes copied to the buffer, including the terminating null
1320 character.
1321
1322 To find out how many bytes you need to store this string as UTF-32, you can call
1323 CharPointer_UTF32::getBytesRequiredFor (myString.getCharPointer())
1324
1325 @param destBuffer the place to copy it to; if this is a null pointer, the method just
1326 returns the number of bytes required (including the terminating null character).
1327 @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the string won't fit, it'll
1328 put in as many as it can while still allowing for a terminating null char at the
1329 end, and will return the number of bytes that were actually used.
1330 @see CharPointer_UTF32::writeWithDestByteLimit
1331 */
1332 size_t copyToUTF32 (CharPointer_UTF32::CharType* destBuffer, size_t maxBufferSizeBytes) const noexcept;
1333
1334 //==============================================================================
1335 /** Increases the string's internally allocated storage.
1336
1337 Although the string's contents won't be affected by this call, it will
1338 increase the amount of memory allocated internally for the string to grow into.
1339
1340 If you're about to make a large number of calls to methods such
1341 as += or <<, it's more efficient to preallocate enough extra space
1342 beforehand, so that these methods won't have to keep resizing the string
1343 to append the extra characters.
1344
1345 @param numBytesNeeded the number of bytes to allocate storage for. If this
1346 value is less than the currently allocated size, it will
1347 have no effect.
1348 */
1349 void preallocateBytes (size_t numBytesNeeded);
1350
1351 /** Swaps the contents of this string with another one.
1352 This is a very fast operation, as no allocation or copying needs to be done.
1353 */
1354 void swapWith (String& other) noexcept;
1355
1356 //==============================================================================
1357 #if JUCE_MAC || JUCE_IOS || DOXYGEN
1358 /** OSX ONLY - Creates a String from an OSX CFString. */
1359 static String fromCFString (CFStringRef cfString);
1360
1361 /** OSX ONLY - Converts this string to a CFString.
1362 Remember that you must use CFRelease() to free the returned string when you're
1363 finished with it.
1364 */
1365 CFStringRef toCFString() const;
1366
1367 /** OSX ONLY - Returns a copy of this string in which any decomposed unicode characters have
1368 been converted to their precomposed equivalents. */
1370 #endif
1371
1372 /** Returns the number of String objects which are currently sharing the same internal
1373 data as this one.
1374 */
1375 int getReferenceCount() const noexcept;
1376
1377 //==============================================================================
1378 /* This was a static empty string object, but is now deprecated as it's too easy to accidentally
1379 use it indirectly during a static constructor, leading to hard-to-find order-of-initialisation
1380 problems.
1381 @deprecated If you need an empty String object, just use String() or {}.
1382 The only time you might miss having String::empty available might be if you need to return an
1383 empty string from a function by reference, but if you need to do that, it's easy enough to use
1384 a function-local static String object and return that, avoiding any order-of-initialisation issues.
1385 */
1386 JUCE_DEPRECATED_STATIC (static const String empty;)
1387
1388private:
1389 //==============================================================================
1390 CharPointerType text;
1391
1392 //==============================================================================
1393 struct PreallocationBytes
1394 {
1395 explicit PreallocationBytes (size_t) noexcept;
1396 size_t numBytes;
1397 };
1398
1399 explicit String (const PreallocationBytes&); // This constructor preallocates a certain amount of memory
1400 size_t getByteOffsetOfEnd() const noexcept;
1401 JUCE_DEPRECATED (String (const String&, size_t));
1402
1403 // This private cast operator should prevent strings being accidentally cast
1404 // to bools (this is possible because the compiler can add an implicit cast
1405 // via a const char*)
1406 operator bool() const noexcept { return false; }
1407
1408 //==============================================================================
1409 static String formattedRaw (const char*, ...);
1410
1411 static String createHex (uint8);
1412 static String createHex (uint16);
1413 static String createHex (uint32);
1414 static String createHex (uint64);
1415
1416 template <typename Type>
1417 static String createHex (Type n) { return createHex (static_cast<typename TypeHelpers::UnsignedTypeWithSize<(int) sizeof (n)>::type> (n)); }
1418};
1419
1420//==============================================================================
1421/** Concatenates two strings. */
1422JUCE_API String JUCE_CALLTYPE operator+ (const char* string1, const String& string2);
1423/** Concatenates two strings. */
1424JUCE_API String JUCE_CALLTYPE operator+ (const wchar_t* string1, const String& string2);
1425/** Concatenates two strings. */
1426JUCE_API String JUCE_CALLTYPE operator+ (char string1, const String& string2);
1427/** Concatenates two strings. */
1428JUCE_API String JUCE_CALLTYPE operator+ (wchar_t string1, const String& string2);
1429#if ! JUCE_NATIVE_WCHAR_IS_UTF32
1430/** Concatenates two strings. */
1431JUCE_API String JUCE_CALLTYPE operator+ (juce_wchar string1, const String& string2);
1432#endif
1433
1434/** Concatenates two strings. */
1435JUCE_API String JUCE_CALLTYPE operator+ (String string1, const String& string2);
1436/** Concatenates two strings. */
1437JUCE_API String JUCE_CALLTYPE operator+ (String string1, const char* string2);
1438/** Concatenates two strings. */
1439JUCE_API String JUCE_CALLTYPE operator+ (String string1, const wchar_t* string2);
1440/** Concatenates two strings. */
1441JUCE_API String JUCE_CALLTYPE operator+ (String string1, const std::string& string2);
1442/** Concatenates two strings. */
1443JUCE_API String JUCE_CALLTYPE operator+ (String string1, char characterToAppend);
1444/** Concatenates two strings. */
1445JUCE_API String JUCE_CALLTYPE operator+ (String string1, wchar_t characterToAppend);
1446#if ! JUCE_NATIVE_WCHAR_IS_UTF32
1447/** Concatenates two strings. */
1448JUCE_API String JUCE_CALLTYPE operator+ (String string1, juce_wchar characterToAppend);
1449#endif
1450
1451//==============================================================================
1452/** Appends a character at the end of a string. */
1453JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, char characterToAppend);
1454/** Appends a character at the end of a string. */
1455JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, wchar_t characterToAppend);
1456#if ! JUCE_NATIVE_WCHAR_IS_UTF32
1457/** Appends a character at the end of a string. */
1458JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, juce_wchar characterToAppend);
1459#endif
1460
1461/** Appends a string to the end of the first one. */
1462JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char* string2);
1463/** Appends a string to the end of the first one. */
1464JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const wchar_t* string2);
1465/** Appends a string to the end of the first one. */
1466JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const String& string2);
1467/** Appends a string to the end of the first one. */
1468JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, StringRef string2);
1469/** Appends a string to the end of the first one. */
1470JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const std::string& string2);
1471
1472/** Appends a decimal number to the end of a string. */
1473JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, uint8 number);
1474/** Appends a decimal number to the end of a string. */
1475JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, short number);
1476/** Appends a decimal number to the end of a string. */
1477JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, int number);
1478/** Appends a decimal number to the end of a string. */
1479JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, long number);
1480/** Appends a decimal number to the end of a string. */
1481JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, unsigned long number);
1482/** Appends a decimal number to the end of a string. */
1483JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, int64 number);
1484/** Appends a decimal number to the end of a string. */
1485JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, uint64 number);
1486/** Appends a decimal number to the end of a string. */
1487JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, float number);
1488/** Appends a decimal number to the end of a string. */
1489JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, double number);
1490
1491#ifndef DOXYGEN
1492// Automatically creating a String from a bool opens up lots of nasty type conversion edge cases.
1493// If you want a String representation of a bool you can cast the bool to an int first.
1494String& JUCE_CALLTYPE operator<< (String&, bool) = delete;
1495#endif
1496
1497//==============================================================================
1498/** Case-sensitive comparison of two strings. */
1499JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) noexcept;
1500/** Case-sensitive comparison of two strings. */
1501JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) noexcept;
1502/** Case-sensitive comparison of two strings. */
1503JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const wchar_t* string2) noexcept;
1504/** Case-sensitive comparison of two strings. */
1505JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, CharPointer_UTF8 string2) noexcept;
1506/** Case-sensitive comparison of two strings. */
1507JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, CharPointer_UTF16 string2) noexcept;
1508/** Case-sensitive comparison of two strings. */
1509JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, CharPointer_UTF32 string2) noexcept;
1510
1511/** Case-sensitive comparison of two strings. */
1512JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) noexcept;
1513/** Case-sensitive comparison of two strings. */
1514JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) noexcept;
1515/** Case-sensitive comparison of two strings. */
1516JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const wchar_t* string2) noexcept;
1517/** Case-sensitive comparison of two strings. */
1518JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, CharPointer_UTF8 string2) noexcept;
1519/** Case-sensitive comparison of two strings. */
1520JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, CharPointer_UTF16 string2) noexcept;
1521/** Case-sensitive comparison of two strings. */
1522JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, CharPointer_UTF32 string2) noexcept;
1523
1524//==============================================================================
1525/** This operator allows you to write a juce String directly to std output streams.
1526 This is handy for writing strings to std::cout, std::cerr, etc.
1527*/
1528template <class traits>
1529std::basic_ostream <char, traits>& JUCE_CALLTYPE operator<< (std::basic_ostream <char, traits>& stream, const String& stringToWrite)
1530{
1531 return stream << stringToWrite.toRawUTF8();
1532}
1533
1534/** This operator allows you to write a juce String directly to std output streams.
1535 This is handy for writing strings to std::wcout, std::wcerr, etc.
1536*/
1537template <class traits>
1538std::basic_ostream <wchar_t, traits>& JUCE_CALLTYPE operator<< (std::basic_ostream <wchar_t, traits>& stream, const String& stringToWrite)
1539{
1540 return stream << stringToWrite.toWideCharPointer();
1541}
1542
1543/** Writes a string to an OutputStream as UTF8. */
1544JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& stringToWrite);
1545
1546/** Writes a string to an OutputStream as UTF8. */
1547JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, StringRef stringToWrite);
1548
1549} // namespace juce
1550
1551#if ! DOXYGEN
1552namespace std
1553{
1554 template <> struct hash<juce::String>
1555 {
1556 size_t operator() (const juce::String& s) const noexcept { return s.hash(); }
1557 };
1558}
1559#endif
1560
1561/** @}*/
Wraps a pointer to a null-terminated ASCII character string, and provides various methods to operate ...
Wraps a pointer to a null-terminated UTF-16 character string, and provides various methods to operate...
Wraps a pointer to a null-terminated UTF-32 character string, and provides various methods to operate...
Wraps a pointer to a null-terminated UTF-8 character string, and provides various methods to operate ...
void writeWithCharLimit(const CharPointer src, const int maxChars) noexcept
Copies a source string to this pointer, advancing this pointer as it goes.
A simple class for holding temporary references to a string literal or String.
The JUCE String class!
Definition: juce_String.h:43
CharPointerType getCharPointer() const noexcept
Returns the character pointer currently being used to store this string.
Definition: juce_String.h:1202
bool isEmpty() const noexcept
Returns true if the string contains no characters.
Definition: juce_String.h:300
static String toDecimalStringWithSignificantFigures(DecimalType number, int numberOfSignificantFigures)
Returns a string containing a decimal with a set number of significant figures.
Definition: juce_String.h:1076
void appendCharPointer(CharPointer startOfTextToAppend, CharPointer endOfTextToAppend)
Appends a string to the end of this one.
Definition: juce_String.h:237
void appendCharPointer(CharPointer textToAppend, size_t maxCharsToTake)
Appends a string to the end of this one.
Definition: juce_String.h:266
void appendCharPointer(CharPointer textToAppend)
Appends a string to the end of this one.
Definition: juce_String.h:288
CFStringRef toCFString() const
OSX ONLY - Converts this string to a CFString.
String convertToPrecomposedUnicode() const
OSX ONLY - Returns a copy of this string in which any decomposed unicode characters have been convert...
static String fromCFString(CFStringRef cfString)
OSX ONLY - Creates a String from an OSX CFString.
bool isNotEmpty() const noexcept
Returns true if the string contains at least one character.
Definition: juce_String.h:306
#define JUCE_API
This macro is added to all JUCE public class declarations.