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 If the string ends with a hyphen followed by numeric characters, the 1053 return value will be negative. 1054 1055 @see getIntValue 1056 */ 1057 int getTrailingIntValue() const noexcept; 1058 1059 /** Parses this string as a floating point number. 1060 1061 @returns the value of the string as a 32-bit floating point value. 1062 @see getDoubleValue 1063 */ 1064 float getFloatValue() const noexcept; 1065 1066 /** Parses this string as a floating point number. 1067 1068 @returns the value of the string as a 64-bit floating point value. 1069 @see getFloatValue 1070 */ 1071 double getDoubleValue() const noexcept; 1072 1073 /** Parses the string as a hexadecimal number. 1074 1075 Non-hexadecimal characters in the string are ignored. 1076 1077 If the string contains too many characters, then the lowest significant 1078 digits are returned, e.g. "ffff12345678" would produce 0x12345678. 1079 1080 @returns a 32-bit number which is the value of the string in hex. 1081 */ 1082 int getHexValue32() const noexcept; 1083 1084 /** Parses the string as a hexadecimal number. 1085 1086 Non-hexadecimal characters in the string are ignored. 1087 1088 If the string contains too many characters, then the lowest significant 1089 digits are returned, e.g. "ffff1234567812345678" would produce 0x1234567812345678. 1090 1091 @returns a 64-bit number which is the value of the string in hex. 1092 */ 1093 int64 getHexValue64() const noexcept; 1094 1095 /** Returns a string representing this numeric value in hexadecimal. */ 1096 template <typename IntegerType> 1097 static String toHexString (IntegerType number) { return createHex (number); } 1098 1099 /** Returns a string containing a hex dump of a block of binary data. 1100 1101 @param data the binary data to use as input 1102 @param size how many bytes of data to use 1103 @param groupSize how many bytes are grouped together before inserting a 1104 space into the output. e.g. group size 0 has no spaces, 1105 group size 1 looks like: "be a1 c2 ff", group size 2 looks 1106 like "bea1 c2ff". 1107 */ 1108 static String toHexString (const void* data, int size, int groupSize = 1); 1109 1110 /** Returns a string containing a decimal with a set number of significant figures. 1111 1112 @param number the input number 1113 @param numberOfSignificantFigures the number of significant figures to use 1114 */ 1115 template <typename DecimalType> 1116 static String toDecimalStringWithSignificantFigures (DecimalType number, int numberOfSignificantFigures) 1117 { 1118 jassert (numberOfSignificantFigures > 0); 1119 1120 if (number == 0) 1121 { 1122 if (numberOfSignificantFigures > 1) 1123 { 1124 String result ("0.0"); 1125 1126 for (int i = 2; i < numberOfSignificantFigures; ++i) 1127 result += "0"; 1128 1129 return result; 1130 } 1131 1132 return "0"; 1133 } 1134 1135 auto numDigitsBeforePoint = (int) std::ceil (std::log10 (number < 0 ? -number : number)); 1136 1137 #if JUCE_PROJUCER_LIVE_BUILD 1138 auto doubleNumber = (double) number; 1139 constexpr int bufferSize = 311; 1140 char buffer[bufferSize]; 1141 auto* ptr = &(buffer[0]); 1142 auto* const safeEnd = ptr + (bufferSize - 1); 1143 auto numSigFigsParsed = 0; 1144 1145 auto writeToBuffer = [safeEnd] (char* destination, char data) 1146 { 1147 *destination++ = data; 1148 1149 if (destination == safeEnd) 1150 { 1151 *destination = '\0'; 1152 return true; 1153 } 1154 1155 return false; 1156 }; 1157 1158 auto truncateOrRound = [numberOfSignificantFigures] (double fractional, int sigFigsParsed) 1159 { 1160 return (sigFigsParsed == numberOfSignificantFigures - 1) ? (int) std::round (fractional) 1161 : (int) fractional; 1162 }; 1163 1164 if (doubleNumber < 0) 1165 { 1166 doubleNumber *= -1; 1167 *ptr++ = '-'; 1168 } 1169 1170 if (numDigitsBeforePoint > 0) 1171 { 1172 doubleNumber /= std::pow (10.0, numDigitsBeforePoint); 1173 1174 while (numDigitsBeforePoint-- > 0) 1175 { 1176 if (numSigFigsParsed == numberOfSignificantFigures) 1177 { 1178 if (writeToBuffer (ptr++, '0')) 1179 return buffer; 1180 1181 continue; 1182 } 1183 1184 doubleNumber *= 10; 1185 auto digit = truncateOrRound (doubleNumber, numSigFigsParsed); 1186 1187 if (writeToBuffer (ptr++, (char) ('0' + digit))) 1188 return buffer; 1189 1190 ++numSigFigsParsed; 1191 doubleNumber -= digit; 1192 } 1193 1194 if (numSigFigsParsed == numberOfSignificantFigures) 1195 { 1196 *ptr++ = '\0'; 1197 return buffer; 1198 } 1199 } 1200 else 1201 { 1202 *ptr++ = '0'; 1203 } 1204 1205 if (writeToBuffer (ptr++, '.')) 1206 return buffer; 1207 1208 while (numSigFigsParsed < numberOfSignificantFigures) 1209 { 1210 doubleNumber *= 10; 1211 auto digit = truncateOrRound (doubleNumber, numSigFigsParsed); 1212 1213 if (writeToBuffer (ptr++, (char) ('0' + digit))) 1214 return buffer; 1215 1216 if (numSigFigsParsed != 0 || digit != 0) 1217 ++numSigFigsParsed; 1218 1219 doubleNumber -= digit; 1220 } 1221 1222 *ptr++ = '\0'; 1223 return buffer; 1224 #else 1225 auto shift = numberOfSignificantFigures - numDigitsBeforePoint; 1226 auto factor = std::pow (10.0, shift); 1227 auto rounded = std::round (number * factor) / factor; 1228 1229 std::stringstream ss; 1230 ss << std::fixed << std::setprecision (std::max (shift, 0)) << rounded; 1231 return ss.str(); 1232 #endif 1233 } 1234 1235 //============================================================================== 1236 /** Returns the character pointer currently being used to store this string. 1237 1238 Because it returns a reference to the string's internal data, the pointer 1239 that is returned must not be stored anywhere, as it can be deleted whenever the 1240 string changes. 1241 */ 1242 CharPointerType getCharPointer() const noexcept { return text; } 1243 1244 /** Returns a pointer to a UTF-8 version of this string. 1245 1246 Because it returns a reference to the string's internal data, the pointer 1247 that is returned must not be stored anywhere, as it can be deleted whenever the 1248 string changes. 1249 1250 To find out how many bytes you need to store this string as UTF-8, you can call 1251 CharPointer_UTF8::getBytesRequiredFor (myString.getCharPointer()) 1252 1253 @see toRawUTF8, getCharPointer, toUTF16, toUTF32 1254 */ 1255 CharPointer_UTF8 toUTF8() const; 1256 1257 /** Returns a pointer to a UTF-8 version of this string. 1258 1259 Because it returns a reference to the string's internal data, the pointer 1260 that is returned must not be stored anywhere, as it can be deleted whenever the 1261 string changes. 1262 1263 To find out how many bytes you need to store this string as UTF-8, you can call 1264 CharPointer_UTF8::getBytesRequiredFor (myString.getCharPointer()) 1265 1266 @see getCharPointer, toUTF8, toUTF16, toUTF32 1267 */ 1268 const char* toRawUTF8() const; 1269 1270 /** Returns a pointer to a UTF-16 version of this string. 1271 1272 Because it returns a reference to the string's internal data, the pointer 1273 that is returned must not be stored anywhere, as it can be deleted whenever the 1274 string changes. 1275 1276 To find out how many bytes you need to store this string as UTF-16, you can call 1277 CharPointer_UTF16::getBytesRequiredFor (myString.getCharPointer()) 1278 1279 @see getCharPointer, toUTF8, toUTF32 1280 */ 1281 CharPointer_UTF16 toUTF16() const; 1282 1283 /** Returns a pointer to a UTF-32 version of this string. 1284 1285 Because it returns a reference to the string's internal data, the pointer 1286 that is returned must not be stored anywhere, as it can be deleted whenever the 1287 string changes. 1288 1289 @see getCharPointer, toUTF8, toUTF16 1290 */ 1291 CharPointer_UTF32 toUTF32() const; 1292 1293 /** Returns a pointer to a wchar_t version of this string. 1294 1295 Because it returns a reference to the string's internal data, the pointer 1296 that is returned must not be stored anywhere, as it can be deleted whenever the 1297 string changes. 1298 1299 Bear in mind that the wchar_t type is different on different platforms, so on 1300 Windows, this will be equivalent to calling toUTF16(), on unix it'll be the same 1301 as calling toUTF32(), etc. 1302 1303 @see getCharPointer, toUTF8, toUTF16, toUTF32 1304 */ 1305 const wchar_t* toWideCharPointer() const; 1306 1307 /** */ 1308 std::string toStdString() const; 1309 1310 //============================================================================== 1311 /** Creates a String from a UTF-8 encoded buffer. 1312 If the size is < 0, it'll keep reading until it hits a zero. 1313 */ 1314 static String fromUTF8 (const char* utf8buffer, int bufferSizeBytes = -1); 1315 1316 /** Returns the number of bytes required to represent this string as UTF8. 1317 The number returned does NOT include the trailing zero. 1318 @see toUTF8, copyToUTF8 1319 */ 1320 size_t getNumBytesAsUTF8() const noexcept; 1321 1322 //============================================================================== 1323 /** Copies the string to a buffer as UTF-8 characters. 1324 1325 Returns the number of bytes copied to the buffer, including the terminating null 1326 character. 1327 1328 To find out how many bytes you need to store this string as UTF-8, you can call 1329 CharPointer_UTF8::getBytesRequiredFor (myString.getCharPointer()) 1330 1331 @param destBuffer the place to copy it to; if this is a null pointer, the method just 1332 returns the number of bytes required (including the terminating null character). 1333 @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the string won't fit, it'll 1334 put in as many as it can while still allowing for a terminating null char at the 1335 end, and will return the number of bytes that were actually used. 1336 @see CharPointer_UTF8::writeWithDestByteLimit 1337 */ 1338 size_t copyToUTF8 (CharPointer_UTF8::CharType* destBuffer, size_t maxBufferSizeBytes) const noexcept; 1339 1340 /** Copies the string to a buffer as UTF-16 characters. 1341 1342 Returns the number of bytes copied to the buffer, including the terminating null 1343 character. 1344 1345 To find out how many bytes you need to store this string as UTF-16, you can call 1346 CharPointer_UTF16::getBytesRequiredFor (myString.getCharPointer()) 1347 1348 @param destBuffer the place to copy it to; if this is a null pointer, the method just 1349 returns the number of bytes required (including the terminating null character). 1350 @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the string won't fit, it'll 1351 put in as many as it can while still allowing for a terminating null char at the 1352 end, and will return the number of bytes that were actually used. 1353 @see CharPointer_UTF16::writeWithDestByteLimit 1354 */ 1355 size_t copyToUTF16 (CharPointer_UTF16::CharType* destBuffer, size_t maxBufferSizeBytes) const noexcept; 1356 1357 /** Copies the string to a buffer as UTF-32 characters. 1358 1359 Returns the number of bytes copied to the buffer, including the terminating null 1360 character. 1361 1362 To find out how many bytes you need to store this string as UTF-32, you can call 1363 CharPointer_UTF32::getBytesRequiredFor (myString.getCharPointer()) 1364 1365 @param destBuffer the place to copy it to; if this is a null pointer, the method just 1366 returns the number of bytes required (including the terminating null character). 1367 @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the string won't fit, it'll 1368 put in as many as it can while still allowing for a terminating null char at the 1369 end, and will return the number of bytes that were actually used. 1370 @see CharPointer_UTF32::writeWithDestByteLimit 1371 */ 1372 size_t copyToUTF32 (CharPointer_UTF32::CharType* destBuffer, size_t maxBufferSizeBytes) const noexcept; 1373 1374 //============================================================================== 1375 /** Increases the string's internally allocated storage. 1376 1377 Although the string's contents won't be affected by this call, it will 1378 increase the amount of memory allocated internally for the string to grow into. 1379 1380 If you're about to make a large number of calls to methods such 1381 as += or <<, it's more efficient to preallocate enough extra space 1382 beforehand, so that these methods won't have to keep resizing the string 1383 to append the extra characters. 1384 1385 @param numBytesNeeded the number of bytes to allocate storage for. If this 1386 value is less than the currently allocated size, it will 1387 have no effect. 1388 */ 1389 void preallocateBytes (size_t numBytesNeeded); 1390 1391 /** Swaps the contents of this string with another one. 1392 This is a very fast operation, as no allocation or copying needs to be done. 1393 */ 1394 void swapWith (String& other) noexcept; 1395 1396 //============================================================================== 1397 #if JUCE_MAC || JUCE_IOS || DOXYGEN 1398 /** OSX ONLY - Creates a String from an OSX CFString. */ 1399 static String fromCFString (CFStringRef cfString); 1400 1401 /** OSX ONLY - Converts this string to a CFString. 1402 Remember that you must use CFRelease() to free the returned string when you're 1403 finished with it. 1404 */ 1405 CFStringRef toCFString() const; 1406 1407 /** OSX ONLY - Returns a copy of this string in which any decomposed unicode characters have 1408 been converted to their precomposed equivalents. */ 1409 String convertToPrecomposedUnicode() const; 1410 #endif 1411 1412 /** Returns the number of String objects which are currently sharing the same internal 1413 data as this one. 1414 */ 1415 int getReferenceCount() const noexcept; 1416 1417 //============================================================================== 1418 /* This was a static empty string object, but is now deprecated as it's too easy to accidentally 1419 use it indirectly during a static constructor, leading to hard-to-find order-of-initialisation 1420 problems. 1421 @deprecated If you need an empty String object, just use String() or {}. 1422 The only time you might miss having String::empty available might be if you need to return an 1423 empty string from a function by reference, but if you need to do that, it's easy enough to use 1424 a function-local static String object and return that, avoiding any order-of-initialisation issues. 1425 */ 1426 JUCE_DEPRECATED_STATIC (static const String empty;) 1427 1428 private: 1429 //============================================================================== 1430 CharPointerType text; 1431 1432 //============================================================================== 1433 struct PreallocationBytes 1434 { 1435 explicit PreallocationBytes (size_t) noexcept; 1436 size_t numBytes; 1437 }; 1438 1439 explicit String (const PreallocationBytes&); // This constructor preallocates a certain amount of memory 1440 size_t getByteOffsetOfEnd() const noexcept; 1441 JUCE_DEPRECATED (String (const String&, size_t)); 1442 1443 // This private cast operator should prevent strings being accidentally cast 1444 // to bools (this is possible because the compiler can add an implicit cast 1445 // via a const char*) 1446 operator bool() const noexcept { return false; } 1447 1448 //============================================================================== 1449 static String formattedRaw (const char*, ...); 1450 1451 static String createHex (uint8); 1452 static String createHex (uint16); 1453 static String createHex (uint32); 1454 static String createHex (uint64); 1455 1456 template <typename Type> 1457 static String createHex (Type n) { return createHex (static_cast<typename TypeHelpers::UnsignedTypeWithSize<(int) sizeof (n)>::type> (n)); } 1458 }; 1459 1460 //============================================================================== 1461 /** Concatenates two strings. */ 1462 JUCE_API String JUCE_CALLTYPE operator+ (const char* string1, const String& string2); 1463 /** Concatenates two strings. */ 1464 JUCE_API String JUCE_CALLTYPE operator+ (const wchar_t* string1, const String& string2); 1465 /** Concatenates two strings. */ 1466 JUCE_API String JUCE_CALLTYPE operator+ (char string1, const String& string2); 1467 /** Concatenates two strings. */ 1468 JUCE_API String JUCE_CALLTYPE operator+ (wchar_t string1, const String& string2); 1469 #if ! JUCE_NATIVE_WCHAR_IS_UTF32 1470 /** Concatenates two strings. */ 1471 JUCE_API String JUCE_CALLTYPE operator+ (juce_wchar string1, const String& string2); 1472 #endif 1473 1474 /** Concatenates two strings. */ 1475 JUCE_API String JUCE_CALLTYPE operator+ (String string1, const String& string2); 1476 /** Concatenates two strings. */ 1477 JUCE_API String JUCE_CALLTYPE operator+ (String string1, const char* string2); 1478 /** Concatenates two strings. */ 1479 JUCE_API String JUCE_CALLTYPE operator+ (String string1, const wchar_t* string2); 1480 /** Concatenates two strings. */ 1481 JUCE_API String JUCE_CALLTYPE operator+ (String string1, const std::string& string2); 1482 /** Concatenates two strings. */ 1483 JUCE_API String JUCE_CALLTYPE operator+ (String string1, char characterToAppend); 1484 /** Concatenates two strings. */ 1485 JUCE_API String JUCE_CALLTYPE operator+ (String string1, wchar_t characterToAppend); 1486 #if ! JUCE_NATIVE_WCHAR_IS_UTF32 1487 /** Concatenates two strings. */ 1488 JUCE_API String JUCE_CALLTYPE operator+ (String string1, juce_wchar characterToAppend); 1489 #endif 1490 1491 //============================================================================== 1492 /** Appends a character at the end of a string. */ 1493 JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, char characterToAppend); 1494 /** Appends a character at the end of a string. */ 1495 JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, wchar_t characterToAppend); 1496 #if ! JUCE_NATIVE_WCHAR_IS_UTF32 1497 /** Appends a character at the end of a string. */ 1498 JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, juce_wchar characterToAppend); 1499 #endif 1500 1501 /** Appends a string to the end of the first one. */ 1502 JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char* string2); 1503 /** Appends a string to the end of the first one. */ 1504 JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const wchar_t* string2); 1505 /** Appends a string to the end of the first one. */ 1506 JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const String& string2); 1507 /** Appends a string to the end of the first one. */ 1508 JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, StringRef string2); 1509 /** Appends a string to the end of the first one. */ 1510 JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const std::string& string2); 1511 1512 /** Appends a decimal number to the end of a string. */ 1513 JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, uint8 number); 1514 /** Appends a decimal number to the end of a string. */ 1515 JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, short number); 1516 /** Appends a decimal number to the end of a string. */ 1517 JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, int number); 1518 /** Appends a decimal number to the end of a string. */ 1519 JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, long number); 1520 /** Appends a decimal number to the end of a string. */ 1521 JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, unsigned long number); 1522 /** Appends a decimal number to the end of a string. */ 1523 JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, int64 number); 1524 /** Appends a decimal number to the end of a string. */ 1525 JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, uint64 number); 1526 /** Appends a decimal number to the end of a string. */ 1527 JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, float number); 1528 /** Appends a decimal number to the end of a string. */ 1529 JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, double number); 1530 1531 #ifndef DOXYGEN 1532 // Automatically creating a String from a bool opens up lots of nasty type conversion edge cases. 1533 // If you want a String representation of a bool you can cast the bool to an int first. 1534 String& JUCE_CALLTYPE operator<< (String&, bool) = delete; 1535 #endif 1536 1537 //============================================================================== 1538 /** Case-sensitive comparison of two strings. */ 1539 JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) noexcept; 1540 /** Case-sensitive comparison of two strings. */ 1541 JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) noexcept; 1542 /** Case-sensitive comparison of two strings. */ 1543 JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const wchar_t* string2) noexcept; 1544 /** Case-sensitive comparison of two strings. */ 1545 JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, CharPointer_UTF8 string2) noexcept; 1546 /** Case-sensitive comparison of two strings. */ 1547 JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, CharPointer_UTF16 string2) noexcept; 1548 /** Case-sensitive comparison of two strings. */ 1549 JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, CharPointer_UTF32 string2) noexcept; 1550 1551 /** Case-sensitive comparison of two strings. */ 1552 JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) noexcept; 1553 /** Case-sensitive comparison of two strings. */ 1554 JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) noexcept; 1555 /** Case-sensitive comparison of two strings. */ 1556 JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const wchar_t* string2) noexcept; 1557 /** Case-sensitive comparison of two strings. */ 1558 JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, CharPointer_UTF8 string2) noexcept; 1559 /** Case-sensitive comparison of two strings. */ 1560 JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, CharPointer_UTF16 string2) noexcept; 1561 /** Case-sensitive comparison of two strings. */ 1562 JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, CharPointer_UTF32 string2) noexcept; 1563 1564 //============================================================================== 1565 /** This operator allows you to write a juce String directly to std output streams. 1566 This is handy for writing strings to std::cout, std::cerr, etc. 1567 */ 1568 template <class traits> 1569 std::basic_ostream <char, traits>& JUCE_CALLTYPE operator<< (std::basic_ostream <char, traits>& stream, const String& stringToWrite) 1570 { 1571 return stream << stringToWrite.toRawUTF8(); 1572 } 1573 1574 /** This operator allows you to write a juce String directly to std output streams. 1575 This is handy for writing strings to std::wcout, std::wcerr, etc. 1576 */ 1577 template <class traits> 1578 std::basic_ostream <wchar_t, traits>& JUCE_CALLTYPE operator<< (std::basic_ostream <wchar_t, traits>& stream, const String& stringToWrite) 1579 { 1580 return stream << stringToWrite.toWideCharPointer(); 1581 } 1582 1583 /** Writes a string to an OutputStream as UTF8. */ 1584 JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& stringToWrite); 1585 1586 /** Writes a string to an OutputStream as UTF8. */ 1587 JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, StringRef stringToWrite); 1588 1589 } // namespace juce 1590 1591 #if ! DOXYGEN 1592 namespace std 1593 { 1594 template <> struct hash<juce::String> 1595 { 1596 size_t operator() (const juce::String& s) const noexcept { return s.hash(); } 1597 }; 1598 } 1599 #endif 1600