The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1511 lines
69KB

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