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