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.

1561 lines
70KB

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