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.
5 // This file defines utility functions for working with strings.
7 #ifndef BASE_STRINGS_STRING_UTIL_H_
8 #define BASE_STRINGS_STRING_UTIL_H_
11 #include <stdarg.h> // va_list
16 #include "base/base_export.h"
17 #include "base/basictypes.h"
18 #include "base/compiler_specific.h"
19 #include "base/strings/string16.h"
20 #include "base/strings/string_piece.h" // For implicit conversions.
24 // C standard-library functions that aren't cross-platform are provided as
25 // "base::...", and their prototypes are listed below. These functions are
26 // then implemented as inline calls to the platform-specific equivalents in the
27 // 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
)
35 // Some of these implementations need to be inlined.
37 // We separate the declaration from the implementation of this inline
38 // function just so the PRINTF_FORMAT works.
39 inline int snprintf(char* buffer
, size_t size
, const char* format
, ...)
41 inline int snprintf(char* buffer
, size_t size
, const char* format
, ...) {
43 va_start(arguments
, format
);
44 int result
= vsnprintf(buffer
, size
, format
, arguments
);
49 // BSD-style safe and consistent string copy functions.
50 // Copies |src| to |dst|, where |dst_size| is the total allocated size of |dst|.
51 // Copies at most |dst_size|-1 characters, and always NULL terminates |dst|, as
52 // long as |dst_size| is not 0. Returns the length of |src| in characters.
53 // If the return value is >= dst_size, then the output was truncated.
54 // NOTE: All sizes are in number of characters, NOT in bytes.
55 BASE_EXPORT
size_t strlcpy(char* dst
, const char* src
, size_t dst_size
);
56 BASE_EXPORT
size_t wcslcpy(wchar_t* dst
, const wchar_t* src
, size_t dst_size
);
58 // Scan a wprintf format string to determine whether it's portable across a
59 // variety of systems. This function only checks that the conversion
60 // specifiers used by the format string are supported and have the same meaning
61 // on a variety of systems. It doesn't check for other errors that might occur
62 // within a format string.
64 // Nonportable conversion specifiers for wprintf are:
65 // - 's' and 'c' without an 'l' length modifier. %s and %c operate on char
66 // data on all systems except Windows, which treat them as wchar_t data.
67 // Use %ls and %lc for wchar_t data instead.
68 // - 'S' and 'C', which operate on wchar_t data on all systems except Windows,
69 // which treat them as char data. Use %ls and %lc for wchar_t data
71 // - 'F', which is not identified by Windows wprintf documentation.
72 // - 'D', 'O', and 'U', which are deprecated and not available on all systems.
73 // Use %ld, %lo, and %lu instead.
75 // Note that there is no portable conversion specifier for char data when
76 // working with wprintf.
78 // This function is intended to be called from base::vswprintf.
79 BASE_EXPORT
bool IsWprintfFormatPortable(const wchar_t* format
);
81 // ASCII-specific tolower. The standard library's tolower is locale sensitive,
82 // so we don't want to use it here.
83 inline char ToLowerASCII(char c
) {
84 return (c
>= 'A' && c
<= 'Z') ? (c
+ ('a' - 'A')) : c
;
86 inline char16
ToLowerASCII(char16 c
) {
87 return (c
>= 'A' && c
<= 'Z') ? (c
+ ('a' - 'A')) : c
;
90 // ASCII-specific toupper. The standard library's toupper is locale sensitive,
91 // so we don't want to use it here.
92 inline char ToUpperASCII(char c
) {
93 return (c
>= 'a' && c
<= 'z') ? (c
+ ('A' - 'a')) : c
;
95 inline char16
ToUpperASCII(char16 c
) {
96 return (c
>= 'a' && c
<= 'z') ? (c
+ ('A' - 'a')) : c
;
99 // Converts the given string to it's ASCII-lowercase equivalent.
100 BASE_EXPORT
std::string
ToLowerASCII(StringPiece str
);
101 BASE_EXPORT string16
ToLowerASCII(StringPiece16 str
);
103 // Converts the given string to it's ASCII-uppercase equivalent.
104 BASE_EXPORT
std::string
ToUpperASCII(StringPiece str
);
105 BASE_EXPORT string16
ToUpperASCII(StringPiece16 str
);
107 // Functor for case-insensitive ASCII comparisons for STL algorithms like
110 // Note that a full Unicode version of this functor is not possible to write
111 // because case mappings might change the number of characters, depend on
112 // context (combining accents), and require handling UTF-16. If you need
113 // proper Unicode support, use base::i18n::ToLower/FoldCase and then just
114 // use a normal operator== on the result.
115 template<typename Char
> struct CaseInsensitiveCompareASCII
{
117 bool operator()(Char x
, Char y
) const {
118 return ToLowerASCII(x
) == ToLowerASCII(y
);
122 // Like strcasecmp for case-insensitive ASCII characters only. Returns:
126 // (unlike strcasecmp which can return values greater or less than 1/-1). For
127 // full Unicode support, use base::i18n::ToLower or base::i18h::FoldCase
128 // and then just call the normal string operators on the result.
129 BASE_EXPORT
int CompareCaseInsensitiveASCII(StringPiece a
, StringPiece b
);
130 BASE_EXPORT
int CompareCaseInsensitiveASCII(StringPiece16 a
, StringPiece16 b
);
132 // Equality for ASCII case-insensitive comparisons. For full Unicode support,
133 // use base::i18n::ToLower or base::i18h::FoldCase and then compare with either
135 BASE_EXPORT
bool EqualsCaseInsensitiveASCII(StringPiece a
, StringPiece b
);
136 BASE_EXPORT
bool EqualsCaseInsensitiveASCII(StringPiece16 a
, StringPiece16 b
);
138 // These threadsafe functions return references to globally unique empty
141 // It is likely faster to construct a new empty string object (just a few
142 // instructions to set the length to 0) than to get the empty string singleton
143 // returned by these functions (which requires threadsafe singleton access).
145 // Therefore, DO NOT USE THESE AS A GENERAL-PURPOSE SUBSTITUTE FOR DEFAULT
146 // CONSTRUCTORS. There is only one case where you should use these: functions
147 // which need to return a string by reference (e.g. as a class member
148 // accessor), and don't have an empty string to use (e.g. in an error case).
149 // These should not be used as initializers, function arguments, or return
150 // values for functions which return by value or outparam.
151 BASE_EXPORT
const std::string
& EmptyString();
152 BASE_EXPORT
const string16
& EmptyString16();
154 // Contains the set of characters representing whitespace in the corresponding
155 // encoding. Null-terminated. The ASCII versions are the whitespaces as defined
156 // by HTML5, and don't include control characters.
157 BASE_EXPORT
extern const wchar_t kWhitespaceWide
[]; // Includes Unicode.
158 BASE_EXPORT
extern const char16 kWhitespaceUTF16
[]; // Includes Unicode.
159 BASE_EXPORT
extern const char kWhitespaceASCII
[];
160 BASE_EXPORT
extern const char16 kWhitespaceASCIIAs16
[]; // No unicode.
162 // Null-terminated string representing the UTF-8 byte order mark.
163 BASE_EXPORT
extern const char kUtf8ByteOrderMark
[];
165 // Removes characters in |remove_chars| from anywhere in |input|. Returns true
166 // if any characters were removed. |remove_chars| must be null-terminated.
167 // NOTE: Safe to use the same variable for both |input| and |output|.
168 BASE_EXPORT
bool RemoveChars(const string16
& input
,
169 const StringPiece16
& remove_chars
,
171 BASE_EXPORT
bool RemoveChars(const std::string
& input
,
172 const StringPiece
& remove_chars
,
173 std::string
* output
);
175 // Replaces characters in |replace_chars| from anywhere in |input| with
176 // |replace_with|. Each character in |replace_chars| will be replaced with
177 // the |replace_with| string. Returns true if any characters were replaced.
178 // |replace_chars| must be null-terminated.
179 // NOTE: Safe to use the same variable for both |input| and |output|.
180 BASE_EXPORT
bool ReplaceChars(const string16
& input
,
181 const StringPiece16
& replace_chars
,
182 const string16
& replace_with
,
184 BASE_EXPORT
bool ReplaceChars(const std::string
& input
,
185 const StringPiece
& replace_chars
,
186 const std::string
& replace_with
,
187 std::string
* output
);
191 TRIM_LEADING
= 1 << 0,
192 TRIM_TRAILING
= 1 << 1,
193 TRIM_ALL
= TRIM_LEADING
| TRIM_TRAILING
,
196 // Removes characters in |trim_chars| from the beginning and end of |input|.
197 // The 8-bit version only works on 8-bit characters, not UTF-8.
199 // It is safe to use the same variable for both |input| and |output| (this is
200 // the normal usage to trim in-place).
201 BASE_EXPORT
bool TrimString(const string16
& input
,
202 StringPiece16 trim_chars
,
204 BASE_EXPORT
bool TrimString(const std::string
& input
,
205 StringPiece trim_chars
,
206 std::string
* output
);
208 // StringPiece versions of the above. The returned pieces refer to the original
210 BASE_EXPORT StringPiece16
TrimString(StringPiece16 input
,
211 const StringPiece16
& trim_chars
,
212 TrimPositions positions
);
213 BASE_EXPORT StringPiece
TrimString(StringPiece input
,
214 const StringPiece
& trim_chars
,
215 TrimPositions positions
);
217 // Truncates a string to the nearest UTF-8 character that will leave
218 // the string less than or equal to the specified byte size.
219 BASE_EXPORT
void TruncateUTF8ToByteSize(const std::string
& input
,
220 const size_t byte_size
,
221 std::string
* output
);
223 // Trims any whitespace from either end of the input string.
225 // The StringPiece versions return a substring referencing the input buffer.
226 // The ASCII versions look only for ASCII whitespace.
228 // The std::string versions return where whitespace was found.
229 // NOTE: Safe to use the same variable for both input and output.
230 BASE_EXPORT TrimPositions
TrimWhitespace(const string16
& input
,
231 TrimPositions positions
,
233 BASE_EXPORT StringPiece16
TrimWhitespace(StringPiece16 input
,
234 TrimPositions positions
);
235 BASE_EXPORT TrimPositions
TrimWhitespaceASCII(const std::string
& input
,
236 TrimPositions positions
,
237 std::string
* output
);
238 BASE_EXPORT StringPiece
TrimWhitespaceASCII(StringPiece input
,
239 TrimPositions positions
);
241 // Deprecated. This function is only for backward compatibility and calls
242 // TrimWhitespaceASCII().
243 BASE_EXPORT TrimPositions
TrimWhitespace(const std::string
& input
,
244 TrimPositions positions
,
245 std::string
* output
);
247 // Searches for CR or LF characters. Removes all contiguous whitespace
248 // strings that contain them. This is useful when trying to deal with text
249 // copied from terminals.
250 // Returns |text|, with the following three transformations:
251 // (1) Leading and trailing whitespace is trimmed.
252 // (2) If |trim_sequences_with_line_breaks| is true, any other whitespace
253 // sequences containing a CR or LF are trimmed.
254 // (3) All other whitespace sequences are converted to single spaces.
255 BASE_EXPORT string16
CollapseWhitespace(
256 const string16
& text
,
257 bool trim_sequences_with_line_breaks
);
258 BASE_EXPORT
std::string
CollapseWhitespaceASCII(
259 const std::string
& text
,
260 bool trim_sequences_with_line_breaks
);
262 // Returns true if |input| is empty or contains only characters found in
264 BASE_EXPORT
bool ContainsOnlyChars(const StringPiece
& input
,
265 const StringPiece
& characters
);
266 BASE_EXPORT
bool ContainsOnlyChars(const StringPiece16
& input
,
267 const StringPiece16
& characters
);
269 // Returns true if the specified string matches the criteria. How can a wide
270 // string be 8-bit or UTF8? It contains only characters that are < 256 (in the
271 // first case) or characters that use only 8-bits and whose 8-bit
272 // representation looks like a UTF-8 string (the second case).
274 // Note that IsStringUTF8 checks not only if the input is structurally
275 // valid but also if it doesn't contain any non-character codepoint
276 // (e.g. U+FFFE). It's done on purpose because all the existing callers want
277 // to have the maximum 'discriminating' power from other encodings. If
278 // there's a use case for just checking the structural validity, we have to
279 // add a new function for that.
281 // IsStringASCII assumes the input is likely all ASCII, and does not leave early
282 // if it is not the case.
283 BASE_EXPORT
bool IsStringUTF8(const StringPiece
& str
);
284 BASE_EXPORT
bool IsStringASCII(const StringPiece
& str
);
285 BASE_EXPORT
bool IsStringASCII(const StringPiece16
& str
);
286 // A convenience adaptor for WebStrings, as they don't convert into
287 // StringPieces directly.
288 BASE_EXPORT
bool IsStringASCII(const string16
& str
);
289 #if defined(WCHAR_T_IS_UTF32)
290 BASE_EXPORT
bool IsStringASCII(const std::wstring
& str
);
293 // Compare the lower-case form of the given string against the given
294 // previously-lower-cased ASCII string (typically a constant).
295 BASE_EXPORT
bool LowerCaseEqualsASCII(StringPiece str
,
296 StringPiece lowecase_ascii
);
297 BASE_EXPORT
bool LowerCaseEqualsASCII(StringPiece16 str
,
298 StringPiece lowecase_ascii
);
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
);
305 // Indicates case sensitivity of comparisons. Only ASCII case insensitivity
306 // is supported. Full Unicode case-insensitive conversions would need to go in
307 // base/i18n so it can use ICU.
309 // If you need to do Unicode-aware case-insensitive StartsWith/EndsWith, it's
310 // best to call base::i18n::ToLower() or base::i18n::FoldCase() (see
311 // base/i18n/case_conversion.h for usage advice) on the arguments, and then use
312 // the results to a case-sensitive comparison.
313 enum class CompareCase
{
318 BASE_EXPORT
bool StartsWith(StringPiece str
,
319 StringPiece search_for
,
320 CompareCase case_sensitivity
);
321 BASE_EXPORT
bool StartsWith(StringPiece16 str
,
322 StringPiece16 search_for
,
323 CompareCase case_sensitivity
);
324 BASE_EXPORT
bool EndsWith(StringPiece str
,
325 StringPiece search_for
,
326 CompareCase case_sensitivity
);
327 BASE_EXPORT
bool EndsWith(StringPiece16 str
,
328 StringPiece16 search_for
,
329 CompareCase case_sensitivity
);
331 // Determines the type of ASCII character, independent of locale (the C
332 // library versions will change based on locale).
333 template <typename Char
>
334 inline bool IsAsciiWhitespace(Char c
) {
335 return c
== ' ' || c
== '\r' || c
== '\n' || c
== '\t';
337 template <typename Char
>
338 inline bool IsAsciiAlpha(Char c
) {
339 return ((c
>= 'A') && (c
<= 'Z')) || ((c
>= 'a') && (c
<= 'z'));
341 template <typename Char
>
342 inline bool IsAsciiDigit(Char c
) {
343 return c
>= '0' && c
<= '9';
346 template <typename Char
>
347 inline bool IsHexDigit(Char c
) {
348 return (c
>= '0' && c
<= '9') ||
349 (c
>= 'A' && c
<= 'F') ||
350 (c
>= 'a' && c
<= 'f');
353 // Returns the integer corresponding to the given hex character. For example:
357 // Assumes the input is a valid hex character. DCHECKs in debug builds if not.
358 BASE_EXPORT
char HexDigitToInt(wchar_t c
);
360 // Returns true if it's a Unicode whitespace character.
361 inline bool IsUnicodeWhitespace(wchar_t c
) {
362 return wcschr(base::kWhitespaceWide
, c
) != NULL
;
365 // Return a byte string in human-readable format with a unit suffix. Not
366 // appropriate for use in any UI; use of FormatBytes and friends in ui/base is
367 // highly recommended instead. TODO(avi): Figure out how to get callers to use
368 // FormatBytes instead; remove this.
369 BASE_EXPORT string16
FormatBytesUnlocalized(int64 bytes
);
371 // Starting at |start_offset| (usually 0), replace the first instance of
372 // |find_this| with |replace_with|.
373 BASE_EXPORT
void ReplaceFirstSubstringAfterOffset(
376 StringPiece16 find_this
,
377 StringPiece16 replace_with
);
378 BASE_EXPORT
void ReplaceFirstSubstringAfterOffset(
381 StringPiece find_this
,
382 StringPiece replace_with
);
384 // Starting at |start_offset| (usually 0), look through |str| and replace all
385 // instances of |find_this| with |replace_with|.
387 // This does entire substrings; use std::replace in <algorithm> for single
388 // characters, for example:
389 // std::replace(str.begin(), str.end(), 'a', 'b');
390 BASE_EXPORT
void ReplaceSubstringsAfterOffset(
393 StringPiece16 find_this
,
394 StringPiece16 replace_with
);
395 BASE_EXPORT
void ReplaceSubstringsAfterOffset(
398 StringPiece find_this
,
399 StringPiece replace_with
);
401 // Reserves enough memory in |str| to accommodate |length_with_null| characters,
402 // sets the size of |str| to |length_with_null - 1| characters, and returns a
403 // pointer to the underlying contiguous array of characters. This is typically
404 // used when calling a function that writes results into a character array, but
405 // the caller wants the data to be managed by a string-like object. It is
406 // convenient in that is can be used inline in the call, and fast in that it
407 // avoids copying the results of the call from a char* into a string.
409 // |length_with_null| must be at least 2, since otherwise the underlying string
410 // would have size 0, and trying to access &((*str)[0]) in that case can result
411 // in a number of problems.
413 // Internally, this takes linear time because the resize() call 0-fills the
414 // underlying array for potentially all
415 // (|length_with_null - 1| * sizeof(string_type::value_type)) bytes. Ideally we
416 // could avoid this aspect of the resize() call, as we expect the caller to
417 // immediately write over this memory, but there is no other way to set the size
418 // of the string, and not doing that will mean people who access |str| rather
419 // than str.c_str() will get back a string of whatever size |str| had on entry
420 // to this function (probably 0).
421 BASE_EXPORT
char* WriteInto(std::string
* str
, size_t length_with_null
);
422 BASE_EXPORT char16
* WriteInto(string16
* str
, size_t length_with_null
);
424 BASE_EXPORT
wchar_t* WriteInto(std::wstring
* str
, size_t length_with_null
);
427 // Does the opposite of SplitString().
428 BASE_EXPORT
std::string
JoinString(const std::vector
<std::string
>& parts
,
429 StringPiece separator
);
430 BASE_EXPORT string16
JoinString(const std::vector
<string16
>& parts
,
431 StringPiece16 separator
);
433 // Replace $1-$2-$3..$9 in the format string with |a|-|b|-|c|..|i| respectively.
434 // Additionally, any number of consecutive '$' characters is replaced by that
435 // number less one. Eg $$->$, $$$->$$, etc. The offsets parameter here can be
436 // NULL. This only allows you to use up to nine replacements.
437 BASE_EXPORT string16
ReplaceStringPlaceholders(
438 const string16
& format_string
,
439 const std::vector
<string16
>& subst
,
440 std::vector
<size_t>* offsets
);
442 BASE_EXPORT
std::string
ReplaceStringPlaceholders(
443 const StringPiece
& format_string
,
444 const std::vector
<std::string
>& subst
,
445 std::vector
<size_t>* offsets
);
447 // Single-string shortcut for ReplaceStringHolders. |offset| may be NULL.
448 BASE_EXPORT string16
ReplaceStringPlaceholders(const string16
& format_string
,
455 #include "base/strings/string_util_win.h"
456 #elif defined(OS_POSIX)
457 #include "base/strings/string_util_posix.h"
459 #error Define string operations appropriately for your platform
462 #endif // BASE_STRINGS_STRING_UTIL_H_