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