string_util.h 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. // Copyright 2013 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. //
  5. // This file defines utility functions for working with strings.
  6. #ifndef BASE_STRINGS_STRING_UTIL_H_
  7. #define BASE_STRINGS_STRING_UTIL_H_
  8. #include <ctype.h>
  9. #include <stdarg.h> // va_list
  10. #include <stddef.h>
  11. #include <stdint.h>
  12. #include <algorithm>
  13. #include <initializer_list>
  14. #include <string>
  15. #include <type_traits>
  16. #include <vector>
  17. #include "base/base_export.h"
  18. #include "base/check_op.h"
  19. #include "base/compiler_specific.h"
  20. #include "base/containers/span.h"
  21. #include "base/cxx20_to_address.h"
  22. #include "base/strings/string_piece.h" // For implicit conversions.
  23. #include "build/build_config.h"
  24. namespace base {
  25. // C standard-library functions that aren't cross-platform are provided as
  26. // "base::...", and their prototypes are listed below. These functions are
  27. // then implemented as inline calls to the platform-specific equivalents in the
  28. // platform-specific headers.
  29. // Wrapper for vsnprintf that always null-terminates and always returns the
  30. // number of characters that would be in an untruncated formatted
  31. // string, even when truncation occurs.
  32. int vsnprintf(char* buffer, size_t size, const char* format, va_list arguments)
  33. PRINTF_FORMAT(3, 0);
  34. // Some of these implementations need to be inlined.
  35. // We separate the declaration from the implementation of this inline
  36. // function just so the PRINTF_FORMAT works.
  37. inline int snprintf(char* buffer, size_t size, const char* format, ...)
  38. PRINTF_FORMAT(3, 4);
  39. inline int snprintf(char* buffer, size_t size, const char* format, ...) {
  40. va_list arguments;
  41. va_start(arguments, format);
  42. int result = vsnprintf(buffer, size, format, arguments);
  43. va_end(arguments);
  44. return result;
  45. }
  46. // BSD-style safe and consistent string copy functions.
  47. // Copies |src| to |dst|, where |dst_size| is the total allocated size of |dst|.
  48. // Copies at most |dst_size|-1 characters, and always NULL terminates |dst|, as
  49. // long as |dst_size| is not 0. Returns the length of |src| in characters.
  50. // If the return value is >= dst_size, then the output was truncated.
  51. // NOTE: All sizes are in number of characters, NOT in bytes.
  52. BASE_EXPORT size_t strlcpy(char* dst, const char* src, size_t dst_size);
  53. BASE_EXPORT size_t wcslcpy(wchar_t* dst, const wchar_t* src, size_t dst_size);
  54. // Scan a wprintf format string to determine whether it's portable across a
  55. // variety of systems. This function only checks that the conversion
  56. // specifiers used by the format string are supported and have the same meaning
  57. // on a variety of systems. It doesn't check for other errors that might occur
  58. // within a format string.
  59. //
  60. // Nonportable conversion specifiers for wprintf are:
  61. // - 's' and 'c' without an 'l' length modifier. %s and %c operate on char
  62. // data on all systems except Windows, which treat them as wchar_t data.
  63. // Use %ls and %lc for wchar_t data instead.
  64. // - 'S' and 'C', which operate on wchar_t data on all systems except Windows,
  65. // which treat them as char data. Use %ls and %lc for wchar_t data
  66. // instead.
  67. // - 'F', which is not identified by Windows wprintf documentation.
  68. // - 'D', 'O', and 'U', which are deprecated and not available on all systems.
  69. // Use %ld, %lo, and %lu instead.
  70. //
  71. // Note that there is no portable conversion specifier for char data when
  72. // working with wprintf.
  73. //
  74. // This function is intended to be called from base::vswprintf.
  75. BASE_EXPORT bool IsWprintfFormatPortable(const wchar_t* format);
  76. // Simplified implementation of C++20's std::basic_string_view(It, End).
  77. // Reference: https://wg21.link/string.view.cons
  78. template <typename CharT, typename Iter>
  79. constexpr BasicStringPiece<CharT> MakeBasicStringPiece(Iter begin, Iter end) {
  80. DCHECK_GE(end - begin, 0);
  81. return {base::to_address(begin), static_cast<size_t>(end - begin)};
  82. }
  83. // Explicit instantiations of MakeBasicStringPiece for the BasicStringPiece
  84. // aliases defined in base/strings/string_piece_forward.h
  85. template <typename Iter>
  86. constexpr StringPiece MakeStringPiece(Iter begin, Iter end) {
  87. return MakeBasicStringPiece<char>(begin, end);
  88. }
  89. template <typename Iter>
  90. constexpr StringPiece16 MakeStringPiece16(Iter begin, Iter end) {
  91. return MakeBasicStringPiece<char16_t>(begin, end);
  92. }
  93. template <typename Iter>
  94. constexpr WStringPiece MakeWStringPiece(Iter begin, Iter end) {
  95. return MakeBasicStringPiece<wchar_t>(begin, end);
  96. }
  97. // ASCII-specific tolower. The standard library's tolower is locale sensitive,
  98. // so we don't want to use it here.
  99. template <typename CharT,
  100. typename = std::enable_if_t<std::is_integral<CharT>::value>>
  101. CharT ToLowerASCII(CharT c) {
  102. return (c >= 'A' && c <= 'Z') ? (c + ('a' - 'A')) : c;
  103. }
  104. // ASCII-specific toupper. The standard library's toupper is locale sensitive,
  105. // so we don't want to use it here.
  106. template <typename CharT,
  107. typename = std::enable_if_t<std::is_integral<CharT>::value>>
  108. CharT ToUpperASCII(CharT c) {
  109. return (c >= 'a' && c <= 'z') ? static_cast<CharT>(c + 'A' - 'a') : c;
  110. }
  111. // Converts the given string to it's ASCII-lowercase equivalent.
  112. BASE_EXPORT std::string ToLowerASCII(StringPiece str);
  113. BASE_EXPORT std::u16string ToLowerASCII(StringPiece16 str);
  114. // Converts the given string to it's ASCII-uppercase equivalent.
  115. BASE_EXPORT std::string ToUpperASCII(StringPiece str);
  116. BASE_EXPORT std::u16string ToUpperASCII(StringPiece16 str);
  117. // Functor for case-insensitive ASCII comparisons for STL algorithms like
  118. // std::search.
  119. //
  120. // Note that a full Unicode version of this functor is not possible to write
  121. // because case mappings might change the number of characters, depend on
  122. // context (combining accents), and require handling UTF-16. If you need
  123. // proper Unicode support, use base::i18n::ToLower/FoldCase and then just
  124. // use a normal operator== on the result.
  125. template<typename Char> struct CaseInsensitiveCompareASCII {
  126. public:
  127. bool operator()(Char x, Char y) const {
  128. return ToLowerASCII(x) == ToLowerASCII(y);
  129. }
  130. };
  131. // Like strcasecmp for case-insensitive ASCII characters only. Returns:
  132. // -1 (a < b)
  133. // 0 (a == b)
  134. // 1 (a > b)
  135. // (unlike strcasecmp which can return values greater or less than 1/-1). For
  136. // full Unicode support, use base::i18n::ToLower or base::i18n::FoldCase
  137. // and then just call the normal string operators on the result.
  138. BASE_EXPORT int CompareCaseInsensitiveASCII(StringPiece a, StringPiece b);
  139. BASE_EXPORT int CompareCaseInsensitiveASCII(StringPiece16 a, StringPiece16 b);
  140. namespace internal {
  141. template <typename CharT, typename CharU>
  142. inline bool EqualsCaseInsensitiveASCIIT(BasicStringPiece<CharT> a,
  143. BasicStringPiece<CharU> b) {
  144. return std::equal(a.begin(), a.end(), b.begin(), b.end(),
  145. [](auto lhs, auto rhs) {
  146. return ToLowerASCII(lhs) == ToLowerASCII(rhs);
  147. });
  148. }
  149. } // namespace internal
  150. // Equality for ASCII case-insensitive comparisons. For full Unicode support,
  151. // use base::i18n::ToLower or base::i18n::FoldCase and then compare with either
  152. // == or !=.
  153. inline bool EqualsCaseInsensitiveASCII(StringPiece a, StringPiece b) {
  154. return internal::EqualsCaseInsensitiveASCIIT(a, b);
  155. }
  156. inline bool EqualsCaseInsensitiveASCII(StringPiece16 a, StringPiece16 b) {
  157. return internal::EqualsCaseInsensitiveASCIIT(a, b);
  158. }
  159. inline bool EqualsCaseInsensitiveASCII(StringPiece16 a, StringPiece b) {
  160. return internal::EqualsCaseInsensitiveASCIIT(a, b);
  161. }
  162. inline bool EqualsCaseInsensitiveASCII(StringPiece a, StringPiece16 b) {
  163. return internal::EqualsCaseInsensitiveASCIIT(a, b);
  164. }
  165. // These threadsafe functions return references to globally unique empty
  166. // strings.
  167. //
  168. // It is likely faster to construct a new empty string object (just a few
  169. // instructions to set the length to 0) than to get the empty string instance
  170. // returned by these functions (which requires threadsafe static access).
  171. //
  172. // Therefore, DO NOT USE THESE AS A GENERAL-PURPOSE SUBSTITUTE FOR DEFAULT
  173. // CONSTRUCTORS. There is only one case where you should use these: functions
  174. // which need to return a string by reference (e.g. as a class member
  175. // accessor), and don't have an empty string to use (e.g. in an error case).
  176. // These should not be used as initializers, function arguments, or return
  177. // values for functions which return by value or outparam.
  178. BASE_EXPORT const std::string& EmptyString();
  179. BASE_EXPORT const std::u16string& EmptyString16();
  180. // Contains the set of characters representing whitespace in the corresponding
  181. // encoding. Null-terminated. The ASCII versions are the whitespaces as defined
  182. // by HTML5, and don't include control characters.
  183. BASE_EXPORT extern const wchar_t kWhitespaceWide[]; // Includes Unicode.
  184. BASE_EXPORT extern const char16_t kWhitespaceUTF16[]; // Includes Unicode.
  185. BASE_EXPORT extern const char16_t
  186. kWhitespaceNoCrLfUTF16[]; // Unicode w/o CR/LF.
  187. BASE_EXPORT extern const char kWhitespaceASCII[];
  188. BASE_EXPORT extern const char16_t kWhitespaceASCIIAs16[]; // No unicode.
  189. // Null-terminated string representing the UTF-8 byte order mark.
  190. BASE_EXPORT extern const char kUtf8ByteOrderMark[];
  191. // Removes characters in |remove_chars| from anywhere in |input|. Returns true
  192. // if any characters were removed. |remove_chars| must be null-terminated.
  193. // NOTE: Safe to use the same variable for both |input| and |output|.
  194. BASE_EXPORT bool RemoveChars(StringPiece16 input,
  195. StringPiece16 remove_chars,
  196. std::u16string* output);
  197. BASE_EXPORT bool RemoveChars(StringPiece input,
  198. StringPiece remove_chars,
  199. std::string* output);
  200. // Replaces characters in |replace_chars| from anywhere in |input| with
  201. // |replace_with|. Each character in |replace_chars| will be replaced with
  202. // the |replace_with| string. Returns true if any characters were replaced.
  203. // |replace_chars| must be null-terminated.
  204. // NOTE: Safe to use the same variable for both |input| and |output|.
  205. BASE_EXPORT bool ReplaceChars(StringPiece16 input,
  206. StringPiece16 replace_chars,
  207. StringPiece16 replace_with,
  208. std::u16string* output);
  209. BASE_EXPORT bool ReplaceChars(StringPiece input,
  210. StringPiece replace_chars,
  211. StringPiece replace_with,
  212. std::string* output);
  213. enum TrimPositions {
  214. TRIM_NONE = 0,
  215. TRIM_LEADING = 1 << 0,
  216. TRIM_TRAILING = 1 << 1,
  217. TRIM_ALL = TRIM_LEADING | TRIM_TRAILING,
  218. };
  219. // Removes characters in |trim_chars| from the beginning and end of |input|.
  220. // The 8-bit version only works on 8-bit characters, not UTF-8. Returns true if
  221. // any characters were removed.
  222. //
  223. // It is safe to use the same variable for both |input| and |output| (this is
  224. // the normal usage to trim in-place).
  225. BASE_EXPORT bool TrimString(StringPiece16 input,
  226. StringPiece16 trim_chars,
  227. std::u16string* output);
  228. BASE_EXPORT bool TrimString(StringPiece input,
  229. StringPiece trim_chars,
  230. std::string* output);
  231. // StringPiece versions of the above. The returned pieces refer to the original
  232. // buffer.
  233. BASE_EXPORT StringPiece16 TrimString(StringPiece16 input,
  234. StringPiece16 trim_chars,
  235. TrimPositions positions);
  236. BASE_EXPORT StringPiece TrimString(StringPiece input,
  237. StringPiece trim_chars,
  238. TrimPositions positions);
  239. // Truncates a string to the nearest UTF-8 character that will leave
  240. // the string less than or equal to the specified byte size.
  241. BASE_EXPORT void TruncateUTF8ToByteSize(const std::string& input,
  242. const size_t byte_size,
  243. std::string* output);
  244. // Trims any whitespace from either end of the input string.
  245. //
  246. // The StringPiece versions return a substring referencing the input buffer.
  247. // The ASCII versions look only for ASCII whitespace.
  248. //
  249. // The std::string versions return where whitespace was found.
  250. // NOTE: Safe to use the same variable for both input and output.
  251. BASE_EXPORT TrimPositions TrimWhitespace(StringPiece16 input,
  252. TrimPositions positions,
  253. std::u16string* output);
  254. BASE_EXPORT StringPiece16 TrimWhitespace(StringPiece16 input,
  255. TrimPositions positions);
  256. BASE_EXPORT TrimPositions TrimWhitespaceASCII(StringPiece input,
  257. TrimPositions positions,
  258. std::string* output);
  259. BASE_EXPORT StringPiece TrimWhitespaceASCII(StringPiece input,
  260. TrimPositions positions);
  261. // Searches for CR or LF characters. Removes all contiguous whitespace
  262. // strings that contain them. This is useful when trying to deal with text
  263. // copied from terminals.
  264. // Returns |text|, with the following three transformations:
  265. // (1) Leading and trailing whitespace is trimmed.
  266. // (2) If |trim_sequences_with_line_breaks| is true, any other whitespace
  267. // sequences containing a CR or LF are trimmed.
  268. // (3) All other whitespace sequences are converted to single spaces.
  269. BASE_EXPORT std::u16string CollapseWhitespace(
  270. StringPiece16 text,
  271. bool trim_sequences_with_line_breaks);
  272. BASE_EXPORT std::string CollapseWhitespaceASCII(
  273. StringPiece text,
  274. bool trim_sequences_with_line_breaks);
  275. // Returns true if |input| is empty or contains only characters found in
  276. // |characters|.
  277. BASE_EXPORT bool ContainsOnlyChars(StringPiece input, StringPiece characters);
  278. BASE_EXPORT bool ContainsOnlyChars(StringPiece16 input,
  279. StringPiece16 characters);
  280. // Returns true if |str| is structurally valid UTF-8 and also doesn't
  281. // contain any non-character code point (e.g. U+10FFFE). Prohibiting
  282. // non-characters increases the likelihood of detecting non-UTF-8 in
  283. // real-world text, for callers which do not need to accept
  284. // non-characters in strings.
  285. BASE_EXPORT bool IsStringUTF8(StringPiece str);
  286. // Returns true if |str| contains valid UTF-8, allowing non-character
  287. // code points.
  288. BASE_EXPORT bool IsStringUTF8AllowingNoncharacters(StringPiece str);
  289. // Returns true if |str| contains only valid ASCII character values.
  290. // Note 1: IsStringASCII executes in time determined solely by the
  291. // length of the string, not by its contents, so it is robust against
  292. // timing attacks for all strings of equal length.
  293. // Note 2: IsStringASCII assumes the input is likely all ASCII, and
  294. // does not leave early if it is not the case.
  295. BASE_EXPORT bool IsStringASCII(StringPiece str);
  296. BASE_EXPORT bool IsStringASCII(StringPiece16 str);
  297. #if defined(WCHAR_T_IS_UTF32)
  298. BASE_EXPORT bool IsStringASCII(WStringPiece str);
  299. #endif
  300. // Performs a case-sensitive string compare of the given 16-bit string against
  301. // the given 8-bit ASCII string (typically a constant). The behavior is
  302. // undefined if the |ascii| string is not ASCII.
  303. BASE_EXPORT bool EqualsASCII(StringPiece16 str, StringPiece ascii);
  304. // Indicates case sensitivity of comparisons. Only ASCII case insensitivity
  305. // is supported. Full Unicode case-insensitive conversions would need to go in
  306. // base/i18n so it can use ICU.
  307. //
  308. // If you need to do Unicode-aware case-insensitive StartsWith/EndsWith, it's
  309. // best to call base::i18n::ToLower() or base::i18n::FoldCase() (see
  310. // base/i18n/case_conversion.h for usage advice) on the arguments, and then use
  311. // the results to a case-sensitive comparison.
  312. enum class CompareCase {
  313. SENSITIVE,
  314. INSENSITIVE_ASCII,
  315. };
  316. BASE_EXPORT bool StartsWith(
  317. StringPiece str,
  318. StringPiece search_for,
  319. CompareCase case_sensitivity = CompareCase::SENSITIVE);
  320. BASE_EXPORT bool StartsWith(
  321. StringPiece16 str,
  322. StringPiece16 search_for,
  323. CompareCase case_sensitivity = CompareCase::SENSITIVE);
  324. BASE_EXPORT bool EndsWith(
  325. StringPiece str,
  326. StringPiece search_for,
  327. CompareCase case_sensitivity = CompareCase::SENSITIVE);
  328. BASE_EXPORT bool EndsWith(
  329. StringPiece16 str,
  330. StringPiece16 search_for,
  331. CompareCase case_sensitivity = CompareCase::SENSITIVE);
  332. // Determines the type of ASCII character, independent of locale (the C
  333. // library versions will change based on locale).
  334. template <typename Char>
  335. inline bool IsAsciiWhitespace(Char c) {
  336. return c == ' ' || c == '\r' || c == '\n' || c == '\t' || c == '\f';
  337. }
  338. template <typename Char>
  339. inline bool IsAsciiAlpha(Char c) {
  340. return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
  341. }
  342. template <typename Char>
  343. inline bool IsAsciiUpper(Char c) {
  344. return c >= 'A' && c <= 'Z';
  345. }
  346. template <typename Char>
  347. inline bool IsAsciiLower(Char c) {
  348. return c >= 'a' && c <= 'z';
  349. }
  350. template <typename Char>
  351. inline bool IsAsciiDigit(Char c) {
  352. return c >= '0' && c <= '9';
  353. }
  354. template <typename Char>
  355. inline bool IsAsciiAlphaNumeric(Char c) {
  356. return IsAsciiAlpha(c) || IsAsciiDigit(c);
  357. }
  358. template <typename Char>
  359. inline bool IsAsciiPrintable(Char c) {
  360. return c >= ' ' && c <= '~';
  361. }
  362. template <typename Char>
  363. inline bool IsHexDigit(Char c) {
  364. return (c >= '0' && c <= '9') ||
  365. (c >= 'A' && c <= 'F') ||
  366. (c >= 'a' && c <= 'f');
  367. }
  368. // Returns the integer corresponding to the given hex character. For example:
  369. // '4' -> 4
  370. // 'a' -> 10
  371. // 'B' -> 11
  372. // Assumes the input is a valid hex character.
  373. BASE_EXPORT char HexDigitToInt(char c);
  374. inline char HexDigitToInt(char16_t c) {
  375. DCHECK(IsHexDigit(c));
  376. return HexDigitToInt(static_cast<char>(c));
  377. }
  378. // Returns true if it's a Unicode whitespace character.
  379. template <typename Char>
  380. inline bool IsUnicodeWhitespace(Char c) {
  381. // kWhitespaceWide is a NUL-terminated string
  382. for (const auto* cur = kWhitespaceWide; *cur; ++cur) {
  383. if (static_cast<typename std::make_unsigned_t<wchar_t>>(*cur) ==
  384. static_cast<typename std::make_unsigned_t<Char>>(c))
  385. return true;
  386. }
  387. return false;
  388. };
  389. // Return a byte string in human-readable format with a unit suffix. Not
  390. // appropriate for use in any UI; use of FormatBytes and friends in ui/base is
  391. // highly recommended instead. TODO(avi): Figure out how to get callers to use
  392. // FormatBytes instead; remove this.
  393. BASE_EXPORT std::u16string FormatBytesUnlocalized(int64_t bytes);
  394. // Starting at |start_offset| (usually 0), replace the first instance of
  395. // |find_this| with |replace_with|.
  396. BASE_EXPORT void ReplaceFirstSubstringAfterOffset(std::u16string* str,
  397. size_t start_offset,
  398. StringPiece16 find_this,
  399. StringPiece16 replace_with);
  400. BASE_EXPORT void ReplaceFirstSubstringAfterOffset(
  401. std::string* str,
  402. size_t start_offset,
  403. StringPiece find_this,
  404. StringPiece replace_with);
  405. // Starting at |start_offset| (usually 0), look through |str| and replace all
  406. // instances of |find_this| with |replace_with|.
  407. //
  408. // This does entire substrings; use std::replace in <algorithm> for single
  409. // characters, for example:
  410. // std::replace(str.begin(), str.end(), 'a', 'b');
  411. BASE_EXPORT void ReplaceSubstringsAfterOffset(std::u16string* str,
  412. size_t start_offset,
  413. StringPiece16 find_this,
  414. StringPiece16 replace_with);
  415. BASE_EXPORT void ReplaceSubstringsAfterOffset(
  416. std::string* str,
  417. size_t start_offset,
  418. StringPiece find_this,
  419. StringPiece replace_with);
  420. // Reserves enough memory in |str| to accommodate |length_with_null| characters,
  421. // sets the size of |str| to |length_with_null - 1| characters, and returns a
  422. // pointer to the underlying contiguous array of characters. This is typically
  423. // used when calling a function that writes results into a character array, but
  424. // the caller wants the data to be managed by a string-like object. It is
  425. // convenient in that is can be used inline in the call, and fast in that it
  426. // avoids copying the results of the call from a char* into a string.
  427. //
  428. // Internally, this takes linear time because the resize() call 0-fills the
  429. // underlying array for potentially all
  430. // (|length_with_null - 1| * sizeof(string_type::value_type)) bytes. Ideally we
  431. // could avoid this aspect of the resize() call, as we expect the caller to
  432. // immediately write over this memory, but there is no other way to set the size
  433. // of the string, and not doing that will mean people who access |str| rather
  434. // than str.c_str() will get back a string of whatever size |str| had on entry
  435. // to this function (probably 0).
  436. BASE_EXPORT char* WriteInto(std::string* str, size_t length_with_null);
  437. BASE_EXPORT char16_t* WriteInto(std::u16string* str, size_t length_with_null);
  438. // Joins a list of strings into a single string, inserting |separator| (which
  439. // may be empty) in between all elements.
  440. //
  441. // Note this is inverse of SplitString()/SplitStringPiece() defined in
  442. // string_split.h.
  443. //
  444. // If possible, callers should build a vector of StringPieces and use the
  445. // StringPiece variant, so that they do not create unnecessary copies of
  446. // strings. For example, instead of using SplitString, modifying the vector,
  447. // then using JoinString, use SplitStringPiece followed by JoinString so that no
  448. // copies of those strings are created until the final join operation.
  449. //
  450. // Use StrCat (in base/strings/strcat.h) if you don't need a separator.
  451. BASE_EXPORT std::string JoinString(span<const std::string> parts,
  452. StringPiece separator);
  453. BASE_EXPORT std::u16string JoinString(span<const std::u16string> parts,
  454. StringPiece16 separator);
  455. BASE_EXPORT std::string JoinString(span<const StringPiece> parts,
  456. StringPiece separator);
  457. BASE_EXPORT std::u16string JoinString(span<const StringPiece16> parts,
  458. StringPiece16 separator);
  459. // Explicit initializer_list overloads are required to break ambiguity when used
  460. // with a literal initializer list (otherwise the compiler would not be able to
  461. // decide between the string and StringPiece overloads).
  462. BASE_EXPORT std::string JoinString(std::initializer_list<StringPiece> parts,
  463. StringPiece separator);
  464. BASE_EXPORT std::u16string JoinString(
  465. std::initializer_list<StringPiece16> parts,
  466. StringPiece16 separator);
  467. // Replace $1-$2-$3..$9 in the format string with values from |subst|.
  468. // Additionally, any number of consecutive '$' characters is replaced by that
  469. // number less one. Eg $$->$, $$$->$$, etc. The offsets parameter here can be
  470. // NULL. This only allows you to use up to nine replacements.
  471. BASE_EXPORT std::u16string ReplaceStringPlaceholders(
  472. StringPiece16 format_string,
  473. const std::vector<std::u16string>& subst,
  474. std::vector<size_t>* offsets);
  475. BASE_EXPORT std::string ReplaceStringPlaceholders(
  476. StringPiece format_string,
  477. const std::vector<std::string>& subst,
  478. std::vector<size_t>* offsets);
  479. // Single-string shortcut for ReplaceStringHolders. |offset| may be NULL.
  480. BASE_EXPORT std::u16string ReplaceStringPlaceholders(
  481. const std::u16string& format_string,
  482. const std::u16string& a,
  483. size_t* offset);
  484. } // namespace base
  485. #if BUILDFLAG(IS_WIN)
  486. #include "base/strings/string_util_win.h"
  487. #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
  488. #include "base/strings/string_util_posix.h"
  489. #else
  490. #error Define string operations appropriately for your platform
  491. #endif
  492. #endif // BASE_STRINGS_STRING_UTIL_H_