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 like "strncasecmp" and "snprintf" that aren't
25 // cross-platform are provided as "base::strncasecmp", and their prototypes
26 // are listed below. These functions are then implemented as inline calls
27 // to the platform-specific equivalents in the platform-specific headers.
29 // Compares the two strings s1 and s2 without regard to case using
30 // the current locale; returns 0 if they are equal, 1 if s1 > s2, and -1 if
31 // s2 > s1 according to a lexicographic comparison.
32 int strcasecmp(const char* s1
, const char* s2
);
34 // Compares up to count characters of s1 and s2 without regard to case using
35 // the current locale; returns 0 if they are equal, 1 if s1 > s2, and -1 if
36 // s2 > s1 according to a lexicographic comparison.
37 int strncasecmp(const char* s1
, const char* s2
, size_t count
);
39 // Same as strncmp but for char16 strings.
40 int strncmp16(const char16
* s1
, const char16
* s2
, size_t count
);
42 // Wrapper for vsnprintf that always null-terminates and always returns the
43 // number of characters that would be in an untruncated formatted
44 // string, even when truncation occurs.
45 int vsnprintf(char* buffer
, size_t size
, const char* format
, va_list arguments
)
48 // Some of these implementations need to be inlined.
50 // We separate the declaration from the implementation of this inline
51 // function just so the PRINTF_FORMAT works.
52 inline int snprintf(char* buffer
, size_t size
, const char* format
, ...)
54 inline int snprintf(char* buffer
, size_t size
, const char* format
, ...) {
56 va_start(arguments
, format
);
57 int result
= vsnprintf(buffer
, size
, format
, arguments
);
62 // BSD-style safe and consistent string copy functions.
63 // Copies |src| to |dst|, where |dst_size| is the total allocated size of |dst|.
64 // Copies at most |dst_size|-1 characters, and always NULL terminates |dst|, as
65 // long as |dst_size| is not 0. Returns the length of |src| in characters.
66 // If the return value is >= dst_size, then the output was truncated.
67 // NOTE: All sizes are in number of characters, NOT in bytes.
68 BASE_EXPORT
size_t strlcpy(char* dst
, const char* src
, size_t dst_size
);
69 BASE_EXPORT
size_t wcslcpy(wchar_t* dst
, const wchar_t* src
, size_t dst_size
);
71 // Scan a wprintf format string to determine whether it's portable across a
72 // variety of systems. This function only checks that the conversion
73 // specifiers used by the format string are supported and have the same meaning
74 // on a variety of systems. It doesn't check for other errors that might occur
75 // within a format string.
77 // Nonportable conversion specifiers for wprintf are:
78 // - 's' and 'c' without an 'l' length modifier. %s and %c operate on char
79 // data on all systems except Windows, which treat them as wchar_t data.
80 // Use %ls and %lc for wchar_t data instead.
81 // - 'S' and 'C', which operate on wchar_t data on all systems except Windows,
82 // which treat them as char data. Use %ls and %lc for wchar_t data
84 // - 'F', which is not identified by Windows wprintf documentation.
85 // - 'D', 'O', and 'U', which are deprecated and not available on all systems.
86 // Use %ld, %lo, and %lu instead.
88 // Note that there is no portable conversion specifier for char data when
89 // working with wprintf.
91 // This function is intended to be called from base::vswprintf.
92 BASE_EXPORT
bool IsWprintfFormatPortable(const wchar_t* format
);
94 // ASCII-specific tolower. The standard library's tolower is locale sensitive,
95 // so we don't want to use it here.
96 template <class Char
> inline Char
ToLowerASCII(Char c
) {
97 return (c
>= 'A' && c
<= 'Z') ? (c
+ ('a' - 'A')) : c
;
100 // ASCII-specific toupper. The standard library's toupper is locale sensitive,
101 // so we don't want to use it here.
102 template <class Char
> inline Char
ToUpperASCII(Char c
) {
103 return (c
>= 'a' && c
<= 'z') ? (c
+ ('A' - 'a')) : c
;
106 // Function objects to aid in comparing/searching strings.
108 template<typename Char
> struct CaseInsensitiveCompare
{
110 bool operator()(Char x
, Char y
) const {
111 // TODO(darin): Do we really want to do locale sensitive comparisons here?
112 // See http://crbug.com/24917
113 return tolower(x
) == tolower(y
);
117 template<typename Char
> struct CaseInsensitiveCompareASCII
{
119 bool operator()(Char x
, Char y
) const {
120 return ToLowerASCII(x
) == ToLowerASCII(y
);
124 // These threadsafe functions return references to globally unique empty
127 // It is likely faster to construct a new empty string object (just a few
128 // instructions to set the length to 0) than to get the empty string singleton
129 // returned by these functions (which requires threadsafe singleton access).
131 // Therefore, DO NOT USE THESE AS A GENERAL-PURPOSE SUBSTITUTE FOR DEFAULT
132 // CONSTRUCTORS. There is only one case where you should use these: functions
133 // which need to return a string by reference (e.g. as a class member
134 // accessor), and don't have an empty string to use (e.g. in an error case).
135 // These should not be used as initializers, function arguments, or return
136 // values for functions which return by value or outparam.
137 BASE_EXPORT
const std::string
& EmptyString();
138 BASE_EXPORT
const string16
& EmptyString16();
140 // Contains the set of characters representing whitespace in the corresponding
141 // encoding. Null-terminated. The ASCII versions are the whitespaces as defined
142 // by HTML5, and don't include control characters.
143 BASE_EXPORT
extern const wchar_t kWhitespaceWide
[]; // Includes Unicode.
144 BASE_EXPORT
extern const char16 kWhitespaceUTF16
[]; // Includes Unicode.
145 BASE_EXPORT
extern const char kWhitespaceASCII
[];
146 BASE_EXPORT
extern const char16 kWhitespaceASCIIAs16
[]; // No unicode.
148 // Null-terminated string representing the UTF-8 byte order mark.
149 BASE_EXPORT
extern const char kUtf8ByteOrderMark
[];
151 // Removes characters in |remove_chars| from anywhere in |input|. Returns true
152 // if any characters were removed. |remove_chars| must be null-terminated.
153 // NOTE: Safe to use the same variable for both |input| and |output|.
154 BASE_EXPORT
bool RemoveChars(const string16
& input
,
155 const base::StringPiece16
& remove_chars
,
157 BASE_EXPORT
bool RemoveChars(const std::string
& input
,
158 const base::StringPiece
& remove_chars
,
159 std::string
* output
);
161 // Replaces characters in |replace_chars| from anywhere in |input| with
162 // |replace_with|. Each character in |replace_chars| will be replaced with
163 // the |replace_with| string. Returns true if any characters were replaced.
164 // |replace_chars| must be null-terminated.
165 // NOTE: Safe to use the same variable for both |input| and |output|.
166 BASE_EXPORT
bool ReplaceChars(const string16
& input
,
167 const base::StringPiece16
& replace_chars
,
168 const string16
& replace_with
,
170 BASE_EXPORT
bool ReplaceChars(const std::string
& input
,
171 const base::StringPiece
& replace_chars
,
172 const std::string
& replace_with
,
173 std::string
* output
);
177 TRIM_LEADING
= 1 << 0,
178 TRIM_TRAILING
= 1 << 1,
179 TRIM_ALL
= TRIM_LEADING
| TRIM_TRAILING
,
182 // Removes characters in |trim_chars| from the beginning and end of |input|.
183 // The 8-bit version only works on 8-bit characters, not UTF-8.
185 // It is safe to use the same variable for both |input| and |output| (this is
186 // the normal usage to trim in-place).
187 BASE_EXPORT
bool TrimString(const string16
& input
,
188 base::StringPiece16 trim_chars
,
190 BASE_EXPORT
bool TrimString(const std::string
& input
,
191 base::StringPiece trim_chars
,
192 std::string
* output
);
194 // StringPiece versions of the above. The returned pieces refer to the original
196 BASE_EXPORT StringPiece16
TrimString(StringPiece16 input
,
197 const base::StringPiece16
& trim_chars
,
198 TrimPositions positions
);
199 BASE_EXPORT StringPiece
TrimString(StringPiece input
,
200 const base::StringPiece
& trim_chars
,
201 TrimPositions positions
);
203 // Truncates a string to the nearest UTF-8 character that will leave
204 // the string less than or equal to the specified byte size.
205 BASE_EXPORT
void TruncateUTF8ToByteSize(const std::string
& input
,
206 const size_t byte_size
,
207 std::string
* output
);
209 // Trims any whitespace from either end of the input string. Returns where
210 // whitespace was found.
211 // The non-wide version has two functions:
212 // * TrimWhitespaceASCII()
213 // This function is for ASCII strings and only looks for ASCII whitespace;
214 // Please choose the best one according to your usage.
215 // NOTE: Safe to use the same variable for both input and output.
216 BASE_EXPORT TrimPositions
TrimWhitespace(const string16
& input
,
217 TrimPositions positions
,
218 base::string16
* output
);
219 BASE_EXPORT TrimPositions
TrimWhitespaceASCII(const std::string
& input
,
220 TrimPositions positions
,
221 std::string
* output
);
223 // Deprecated. This function is only for backward compatibility and calls
224 // TrimWhitespaceASCII().
225 BASE_EXPORT TrimPositions
TrimWhitespace(const std::string
& input
,
226 TrimPositions positions
,
227 std::string
* output
);
229 // Searches for CR or LF characters. Removes all contiguous whitespace
230 // strings that contain them. This is useful when trying to deal with text
231 // copied from terminals.
232 // Returns |text|, with the following three transformations:
233 // (1) Leading and trailing whitespace is trimmed.
234 // (2) If |trim_sequences_with_line_breaks| is true, any other whitespace
235 // sequences containing a CR or LF are trimmed.
236 // (3) All other whitespace sequences are converted to single spaces.
237 BASE_EXPORT string16
CollapseWhitespace(
238 const string16
& text
,
239 bool trim_sequences_with_line_breaks
);
240 BASE_EXPORT
std::string
CollapseWhitespaceASCII(
241 const std::string
& text
,
242 bool trim_sequences_with_line_breaks
);
244 // Returns true if |input| is empty or contains only characters found in
246 BASE_EXPORT
bool ContainsOnlyChars(const StringPiece
& input
,
247 const StringPiece
& characters
);
248 BASE_EXPORT
bool ContainsOnlyChars(const StringPiece16
& input
,
249 const StringPiece16
& characters
);
251 // Returns true if the specified string matches the criteria. How can a wide
252 // string be 8-bit or UTF8? It contains only characters that are < 256 (in the
253 // first case) or characters that use only 8-bits and whose 8-bit
254 // representation looks like a UTF-8 string (the second case).
256 // Note that IsStringUTF8 checks not only if the input is structurally
257 // valid but also if it doesn't contain any non-character codepoint
258 // (e.g. U+FFFE). It's done on purpose because all the existing callers want
259 // to have the maximum 'discriminating' power from other encodings. If
260 // there's a use case for just checking the structural validity, we have to
261 // add a new function for that.
263 // IsStringASCII assumes the input is likely all ASCII, and does not leave early
264 // if it is not the case.
265 BASE_EXPORT
bool IsStringUTF8(const StringPiece
& str
);
266 BASE_EXPORT
bool IsStringASCII(const StringPiece
& str
);
267 BASE_EXPORT
bool IsStringASCII(const StringPiece16
& str
);
268 // A convenience adaptor for WebStrings, as they don't convert into
269 // StringPieces directly.
270 BASE_EXPORT
bool IsStringASCII(const string16
& str
);
271 #if defined(WCHAR_T_IS_UTF32)
272 BASE_EXPORT
bool IsStringASCII(const std::wstring
& str
);
275 // Converts the elements of the given string. This version uses a pointer to
276 // clearly differentiate it from the non-pointer variant.
277 template <class str
> inline void StringToLowerASCII(str
* s
) {
278 for (typename
str::iterator i
= s
->begin(); i
!= s
->end(); ++i
)
279 *i
= ToLowerASCII(*i
);
282 template <class str
> inline str
StringToLowerASCII(const str
& s
) {
283 // for std::string and std::wstring
285 StringToLowerASCII(&output
);
289 // Converts the elements of the given string. This version uses a pointer to
290 // clearly differentiate it from the non-pointer variant.
291 template <class str
> inline void StringToUpperASCII(str
* s
) {
292 for (typename
str::iterator i
= s
->begin(); i
!= s
->end(); ++i
)
293 *i
= ToUpperASCII(*i
);
296 template <class str
> inline str
StringToUpperASCII(const str
& s
) {
297 // for std::string and std::wstring
299 StringToUpperASCII(&output
);
303 // Compare the lower-case form of the given string against the given ASCII
304 // string. This is useful for doing checking if an input string matches some
305 // token, and it is optimized to avoid intermediate string copies. This API is
306 // borrowed from the equivalent APIs in Mozilla.
307 BASE_EXPORT
bool LowerCaseEqualsASCII(const std::string
& a
, const char* b
);
308 BASE_EXPORT
bool LowerCaseEqualsASCII(const string16
& a
, const char* b
);
310 // Same thing, but with string iterators instead.
311 BASE_EXPORT
bool LowerCaseEqualsASCII(std::string::const_iterator a_begin
,
312 std::string::const_iterator a_end
,
314 BASE_EXPORT
bool LowerCaseEqualsASCII(string16::const_iterator a_begin
,
315 string16::const_iterator a_end
,
317 BASE_EXPORT
bool LowerCaseEqualsASCII(const char* a_begin
,
320 BASE_EXPORT
bool LowerCaseEqualsASCII(const char* a_begin
,
324 BASE_EXPORT
bool LowerCaseEqualsASCII(const char16
* a_begin
,
328 // Performs a case-sensitive string compare. The behavior is undefined if both
329 // strings are not ASCII.
330 BASE_EXPORT
bool EqualsASCII(const string16
& a
, const StringPiece
& b
);
332 // Indicates case sensitivity of comparisons. Only ASCII case insensitivity
333 // is supported. Full Unicode case-insensitive conversions would need to go in
334 // base/i18n so it can use ICU.
336 // If you need to do Unicode-aware case-insensitive StartsWith/EndsWith, it's
337 // best to just call base::i18n::ToLower() on the arguements, and then use the
338 // results to a case-sensitive comparison.
339 enum class CompareCase
{
344 BASE_EXPORT
bool StartsWith(StringPiece str
,
345 StringPiece search_for
,
346 CompareCase case_sensitivity
);
347 BASE_EXPORT
bool StartsWith(StringPiece16 str
,
348 StringPiece16 search_for
,
349 CompareCase case_sensitivity
);
350 BASE_EXPORT
bool EndsWith(StringPiece str
,
351 StringPiece search_for
,
352 CompareCase case_sensitivity
);
353 BASE_EXPORT
bool EndsWith(StringPiece16 str
,
354 StringPiece16 search_for
,
355 CompareCase case_sensitivity
);
357 // DEPRECATED. Returns true if str starts/ends with search, or false otherwise.
358 // TODO(brettw) remove in favor of the "enum" versions above.
359 inline bool StartsWithASCII(const std::string
& str
,
360 const std::string
& search
,
361 bool case_sensitive
) {
362 return StartsWith(StringPiece(str
), StringPiece(search
),
363 case_sensitive
? CompareCase::SENSITIVE
364 : CompareCase::INSENSITIVE_ASCII
);
366 BASE_EXPORT
bool StartsWith(const string16
& str
,
367 const string16
& search
,
368 bool case_sensitive
);
369 inline bool EndsWith(const std::string
& str
,
370 const std::string
& search
,
371 bool case_sensitive
) {
372 return EndsWith(StringPiece(str
), StringPiece(search
),
373 case_sensitive
? CompareCase::SENSITIVE
374 : CompareCase::INSENSITIVE_ASCII
);
376 BASE_EXPORT
bool EndsWith(const string16
& str
,
377 const string16
& search
,
378 bool case_sensitive
);
383 #include "base/strings/string_util_win.h"
384 #elif defined(OS_POSIX)
385 #include "base/strings/string_util_posix.h"
387 #error Define string operations appropriately for your platform
390 // Determines the type of ASCII character, independent of locale (the C
391 // library versions will change based on locale).
392 template <typename Char
>
393 inline bool IsAsciiWhitespace(Char c
) {
394 return c
== ' ' || c
== '\r' || c
== '\n' || c
== '\t';
396 template <typename Char
>
397 inline bool IsAsciiAlpha(Char c
) {
398 return ((c
>= 'A') && (c
<= 'Z')) || ((c
>= 'a') && (c
<= 'z'));
400 template <typename Char
>
401 inline bool IsAsciiDigit(Char c
) {
402 return c
>= '0' && c
<= '9';
405 template <typename Char
>
406 inline bool IsHexDigit(Char c
) {
407 return (c
>= '0' && c
<= '9') ||
408 (c
>= 'A' && c
<= 'F') ||
409 (c
>= 'a' && c
<= 'f');
412 template <typename Char
>
413 inline char HexDigitToInt(Char c
) {
414 DCHECK(IsHexDigit(c
));
415 if (c
>= '0' && c
<= '9')
416 return static_cast<char>(c
- '0');
417 if (c
>= 'A' && c
<= 'F')
418 return static_cast<char>(c
- 'A' + 10);
419 if (c
>= 'a' && c
<= 'f')
420 return static_cast<char>(c
- 'a' + 10);
424 // Returns true if it's a whitespace character.
425 inline bool IsWhitespace(wchar_t c
) {
426 return wcschr(base::kWhitespaceWide
, c
) != NULL
;
429 // Return a byte string in human-readable format with a unit suffix. Not
430 // appropriate for use in any UI; use of FormatBytes and friends in ui/base is
431 // highly recommended instead. TODO(avi): Figure out how to get callers to use
432 // FormatBytes instead; remove this.
433 BASE_EXPORT
base::string16
FormatBytesUnlocalized(int64 bytes
);
435 // Starting at |start_offset| (usually 0), replace the first instance of
436 // |find_this| with |replace_with|.
437 BASE_EXPORT
void ReplaceFirstSubstringAfterOffset(
440 const base::string16
& find_this
,
441 const base::string16
& replace_with
);
442 BASE_EXPORT
void ReplaceFirstSubstringAfterOffset(
445 const std::string
& find_this
,
446 const std::string
& replace_with
);
448 // Starting at |start_offset| (usually 0), look through |str| and replace all
449 // instances of |find_this| with |replace_with|.
451 // This does entire substrings; use std::replace in <algorithm> for single
452 // characters, for example:
453 // std::replace(str.begin(), str.end(), 'a', 'b');
454 BASE_EXPORT
void ReplaceSubstringsAfterOffset(
457 const base::string16
& find_this
,
458 const base::string16
& replace_with
);
459 BASE_EXPORT
void ReplaceSubstringsAfterOffset(std::string
* str
,
461 const std::string
& find_this
,
462 const std::string
& replace_with
);
464 // Reserves enough memory in |str| to accommodate |length_with_null| characters,
465 // sets the size of |str| to |length_with_null - 1| characters, and returns a
466 // pointer to the underlying contiguous array of characters. This is typically
467 // used when calling a function that writes results into a character array, but
468 // the caller wants the data to be managed by a string-like object. It is
469 // convenient in that is can be used inline in the call, and fast in that it
470 // avoids copying the results of the call from a char* into a string.
472 // |length_with_null| must be at least 2, since otherwise the underlying string
473 // would have size 0, and trying to access &((*str)[0]) in that case can result
474 // in a number of problems.
476 // Internally, this takes linear time because the resize() call 0-fills the
477 // underlying array for potentially all
478 // (|length_with_null - 1| * sizeof(string_type::value_type)) bytes. Ideally we
479 // could avoid this aspect of the resize() call, as we expect the caller to
480 // immediately write over this memory, but there is no other way to set the size
481 // of the string, and not doing that will mean people who access |str| rather
482 // than str.c_str() will get back a string of whatever size |str| had on entry
483 // to this function (probably 0).
484 template <class string_type
>
485 inline typename
string_type::value_type
* WriteInto(string_type
* str
,
486 size_t length_with_null
) {
487 DCHECK_GT(length_with_null
, 1u);
488 str
->reserve(length_with_null
);
489 str
->resize(length_with_null
- 1);
493 //-----------------------------------------------------------------------------
495 // Splits a string into its fields delimited by any of the characters in
496 // |delimiters|. Each field is added to the |tokens| vector. Returns the
497 // number of tokens found.
499 // DEPRECATED. Use SplitStringUsingSet for new code (these just forward).
500 // TODO(brettw) convert callers and delete these forwarders.
501 BASE_EXPORT
size_t Tokenize(const base::string16
& str
,
502 const base::string16
& delimiters
,
503 std::vector
<base::string16
>* tokens
);
504 BASE_EXPORT
size_t Tokenize(const std::string
& str
,
505 const std::string
& delimiters
,
506 std::vector
<std::string
>* tokens
);
507 BASE_EXPORT
size_t Tokenize(const base::StringPiece
& str
,
508 const base::StringPiece
& delimiters
,
509 std::vector
<base::StringPiece
>* tokens
);
511 // Does the opposite of SplitString().
512 BASE_EXPORT
base::string16
JoinString(const std::vector
<base::string16
>& parts
,
514 BASE_EXPORT
std::string
JoinString(
515 const std::vector
<std::string
>& parts
, char s
);
517 // Join |parts| using |separator|.
518 BASE_EXPORT
std::string
JoinString(
519 const std::vector
<std::string
>& parts
,
520 const std::string
& separator
);
521 BASE_EXPORT
base::string16
JoinString(
522 const std::vector
<base::string16
>& parts
,
523 const base::string16
& separator
);
525 // Replace $1-$2-$3..$9 in the format string with |a|-|b|-|c|..|i| respectively.
526 // Additionally, any number of consecutive '$' characters is replaced by that
527 // number less one. Eg $$->$, $$$->$$, etc. The offsets parameter here can be
528 // NULL. This only allows you to use up to nine replacements.
529 BASE_EXPORT
base::string16
ReplaceStringPlaceholders(
530 const base::string16
& format_string
,
531 const std::vector
<base::string16
>& subst
,
532 std::vector
<size_t>* offsets
);
534 BASE_EXPORT
std::string
ReplaceStringPlaceholders(
535 const base::StringPiece
& format_string
,
536 const std::vector
<std::string
>& subst
,
537 std::vector
<size_t>* offsets
);
539 // Single-string shortcut for ReplaceStringHolders. |offset| may be NULL.
540 BASE_EXPORT
base::string16
ReplaceStringPlaceholders(
541 const base::string16
& format_string
,
542 const base::string16
& a
,
545 // Returns true if the string passed in matches the pattern. The pattern
546 // string can contain wildcards like * and ?
547 // The backslash character (\) is an escape character for * and ?
548 // We limit the patterns to having a max of 16 * or ? characters.
549 // ? matches 0 or 1 character, while * matches 0 or more characters.
550 BASE_EXPORT
bool MatchPattern(const base::StringPiece
& string
,
551 const base::StringPiece
& pattern
);
552 BASE_EXPORT
bool MatchPattern(const base::string16
& string
,
553 const base::string16
& pattern
);
555 #endif // BASE_STRINGS_STRING_UTIL_H_