All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
stringUtils.h
Go to the documentation of this file.
1 //
2 // Copyright 2016 Pixar
3 //
4 // Licensed under the Apache License, Version 2.0 (the "Apache License")
5 // with the following modification; you may not use this file except in
6 // compliance with the Apache License and the following modification to it:
7 // Section 6. Trademarks. is deleted and replaced with:
8 //
9 // 6. Trademarks. This License does not grant permission to use the trade
10 // names, trademarks, service marks, or product names of the Licensor
11 // and its affiliates, except as required to comply with Section 4(c) of
12 // the License and to reproduce the content of the NOTICE file.
13 //
14 // You may obtain a copy of the Apache License at
15 //
16 // http://www.apache.org/licenses/LICENSE-2.0
17 //
18 // Unless required by applicable law or agreed to in writing, software
19 // distributed under the Apache License with the above modification is
20 // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
21 // KIND, either express or implied. See the Apache License for the specific
22 // language governing permissions and limitations under the Apache License.
23 //
24 #ifndef TF_STRINGUTILS_H
25 #define TF_STRINGUTILS_H
26 
30 
31 #include "pxr/pxr.h"
32 
33 #include "pxr/base/arch/attributes.h"
34 #include "pxr/base/arch/inttypes.h"
35 #include "pxr/base/tf/api.h"
36 #include "pxr/base/tf/enum.h"
37 
38 #include <cstdarg>
39 #include <cstring>
40 #include <list>
41 #include <set>
42 #include <sstream>
43 #include <string>
44 #include <type_traits>
45 #include <vector>
46 
47 PXR_NAMESPACE_OPEN_SCOPE
48 
49 class TfToken;
50 
53 
71 TF_API
72 std::string TfStringPrintf(const char *fmt, ...)
73 #ifndef doxygen
75 #endif /* doxygen */
76  ;
77 
87 TF_API
88 std::string TfVStringPrintf(const std::string& fmt, va_list ap);
89 
91 
92 TF_API
93 std::string TfVStringPrintf(const char *fmt, va_list ap)
94 #ifndef doxygen
96 #endif /* doxygen */
97  ;
98 
102 inline std::string TfSafeString(const char* ptr) {
103  return ptr ? std::string(ptr) : std::string();
104 }
105 
107 inline std::string TfIntToString(int i) {
108  return TfStringPrintf("%d", i);
109 }
110 
130 TF_API double TfStringToDouble(const std::string& txt);
131 
133 TF_API double TfStringToDouble(const char *text);
134 
146 TF_API
147 long TfStringToLong(const std::string &txt, bool *outOfRange=NULL);
148 
150 
151 TF_API
152 long TfStringToLong(const char *txt, bool *outOfRange=NULL);
153 
164 TF_API
165 unsigned long TfStringToULong(const std::string &txt, bool *outOfRange=NULL);
166 
168 
169 TF_API
170 unsigned long TfStringToULong(const char *txt, bool *outOfRange=NULL);
171 
183 TF_API
184 int64_t TfStringToInt64(const std::string &txt, bool *outOfRange=NULL);
185 
187 TF_API
188 int64_t TfStringToInt64(const char *txt, bool *outOfRange=NULL);
189 
200 TF_API
201 uint64_t TfStringToUInt64(const std::string &txt, bool *outOfRange=NULL);
202 
204 TF_API
205 uint64_t TfStringToUInt64(const char *txt, bool *outOfRange=NULL);
206 
207 inline bool
208 Tf_StringStartsWithImpl(char const *s, size_t slen,
209  char const *prefix, size_t prelen)
210 {
211  return slen >= prelen && strncmp(s, prefix, prelen) == 0;
212 }
213 
215 inline bool
216 TfStringStartsWith(const std::string& s, const char *prefix)
217 {
218  return Tf_StringStartsWithImpl(
219  s.c_str(), s.length(), prefix, strlen(prefix));
220 }
221 
223 inline bool
224 TfStringStartsWith(const std::string& s, const std::string& prefix) {
225  return TfStringStartsWith(s, prefix.c_str());
226 }
227 
229 TF_API
230 bool TfStringStartsWith(const std::string &s, const TfToken& prefix);
231 
232 inline bool
233 Tf_StringEndsWithImpl(char const *s, size_t slen,
234  char const *suffix, size_t suflen)
235 {
236  return slen >= suflen && strcmp(s + (slen - suflen), suffix) == 0;
237 }
238 
240 inline bool TfStringEndsWith(const std::string& s, const char *suffix)
241 {
242  return Tf_StringEndsWithImpl(s.c_str(), s.length(),
243  suffix, strlen(suffix));
244 }
245 
247 inline bool
248 TfStringEndsWith(const std::string& s, const std::string& suffix)
249 {
250  return TfStringEndsWith(s, suffix.c_str());
251 }
252 
254 TF_API
255 bool TfStringEndsWith(const std::string &s, const TfToken& suffix);
256 
258 // \ingroup group_tf_String
259 TF_API
260 bool TfStringContains(const std::string& s, const char *substring);
261 
263 inline bool
264 TfStringContains(const std::string &s, const std::string &substring) {
265  return TfStringContains(s, substring.c_str());
266 }
267 
269 TF_API
270 bool TfStringContains(const std::string &s, const TfToken& substring);
271 
273 TF_API
274 std::string TfStringToLower(const std::string& source);
275 
277 TF_API
278 std::string TfStringToUpper(const std::string& source);
279 
282 TF_API
283 std::string TfStringCapitalize(const std::string& source);
284 
289 TF_API
290 std::string TfStringTrimLeft(const std::string& s,
291  const char* trimChars = " \n\t\r");
292 
297 TF_API
298 std::string TfStringTrimRight(const std::string& s,
299  const char* trimChars = " \n\t\r");
300 
306 TF_API
307 std::string TfStringTrim(const std::string& s,
308  const char* trimChars = " \n\t\r");
309 
315 TF_API
316 std::string TfStringGetCommonPrefix(std::string a, std::string b);
317 
323 TF_API
324 std::string TfStringGetSuffix(const std::string& name, char delimiter = '.');
325 
332 TF_API
333 std::string TfStringGetBeforeSuffix(const std::string& name, char delimiter = '.');
334 
336 TF_API
337 std::string TfGetBaseName(const std::string& fileName);
338 
346 TF_API
347 std::string TfGetPathName(const std::string& fileName);
348 
354 TF_API
355 std::string TfStringReplace(const std::string& source, const std::string& from,
356  const std::string& to);
357 
363 template <class ForwardIterator>
364 std::string TfStringJoin(
365  ForwardIterator begin, ForwardIterator end,
366  const char* separator = " ")
367 {
368  if (begin == end)
369  return std::string();
370 
371  size_t distance = std::distance(begin, end);
372  if (distance == 1)
373  return *begin;
374 
375  std::string retVal;
376 
377  size_t sum = 0;
378  ForwardIterator i = begin;
379  for (i = begin; i != end; ++i)
380  sum += i->size();
381  retVal.reserve(sum + strlen(separator) * (distance - 1));
382 
383  i = begin;
384  retVal.append(*i);
385  while (++i != end) {
386  retVal.append(separator);
387  retVal.append(*i);
388  }
389 
390  return retVal;
391 }
392 
397 TF_API
398 std::string TfStringJoin(const std::vector<std::string>& strings,
399  const char* separator = " ");
400 
405 TF_API
406 std::string TfStringJoin(const std::set<std::string>& strings,
407  const char* separator = " ");
408 
414 TF_API
415 std::vector<std::string> TfStringSplit(std::string const &src,
416  std::string const &separator);
417 
423 TF_API
424 std::vector<std::string> TfStringTokenize(const std::string& source,
425  const char* delimiters = " \t\n");
426 
430 TF_API
431 std::set<std::string> TfStringTokenizeToSet(const std::string& source,
432  const char* delimiters = " \t\n");
433 
443 TF_API
444 std::vector<std::string>
445 TfQuotedStringTokenize(const std::string& source,
446  const char* delimiters = " \t\n",
447  std::string *errors = NULL);
448 
459 TF_API
460 std::vector<std::string>
461 TfMatchedStringTokenize(const std::string& source,
462  char openDelimiter,
463  char closeDelimiter,
464  char escapeCharacter = '\0',
465  std::string *errors = NULL);
466 
473 inline
474 std::vector<std::string>
475 TfMatchedStringTokenize(const std::string& source,
476  char openDelimiter,
477  char closeDelimiter,
478  std::string *errors)
479 {
480  return TfMatchedStringTokenize(source, openDelimiter,
481  closeDelimiter, '\0', errors);
482 }
483 
513  TF_API bool operator()(const std::string &lhs, const std::string &rhs) const;
514 };
515 
521 template <typename T>
522 typename std::enable_if<!std::is_enum<T>::value, std::string>::type
523 TfStringify(const T& v)
524 {
525  std::ostringstream stream;
526  stream << v;
527  return stream.str();
528 }
529 
531 template <typename T>
532 typename std::enable_if<std::is_enum<T>::value, std::string>::type
533 TfStringify(const T& v)
534 {
535  return TfEnum::GetName(v);
536 }
537 
539 TF_API std::string TfStringify(bool v);
541 TF_API std::string TfStringify(std::string const&);
543 TF_API std::string TfStringify(float);
545 TF_API std::string TfStringify(double);
546 
553 TF_API bool TfDoubleToString(
554  double d, char* buffer, int len, bool emitTrailingZero);
555 
561  explicit TfStreamFloat(float f) : value(f) {}
562  float value;
563 };
564 
565 TF_API std::ostream& operator<<(std::ostream& o, TfStreamFloat t);
566 
572  explicit TfStreamDouble(double d) : value(d) {}
573  double value;
574 };
575 
576 TF_API std::ostream& operator<<(std::ostream& o, TfStreamDouble t);
577 
583 template <typename T>
584 T
585 TfUnstringify(const std::string &instring, bool* status = NULL)
586 {
587  T v = T();
588  std::istringstream stream(instring);
589  stream >> v;
590  if (status && !stream)
591  *status = false;
592  return v;
593 }
594 
596 template <>
597 TF_API
598 bool TfUnstringify(const std::string &instring, bool* status);
600 template <>
601 TF_API
602 std::string TfUnstringify(const std::string &instring, bool* status);
603 
609 TF_API
610 std::string TfStringGlobToRegex(const std::string& s);
611 
636 TF_API std::string TfEscapeString(const std::string &in);
637 TF_API void TfEscapeStringReplaceChar(const char** in, char** out);
638 
649 TF_API
650 std::string TfStringCatPaths( const std::string &prefix,
651  const std::string &suffix );
652 
658 inline bool
659 TfIsValidIdentifier(std::string const &identifier)
660 {
661  char const *p = identifier.c_str();
662  auto letter = [](unsigned c) { return ((c-'A') < 26) || ((c-'a') < 26); };
663  auto number = [](unsigned c) { return (c-'0') < 10; };
664  auto under = [](unsigned c) { return c == '_'; };
665  unsigned x = *p;
666  if (!x || number(x)) {
667  return false;
668  }
669  while (letter(x) || number(x) || under(x)) {
670  x = *p++;
671  };
672  return x == 0;
673 }
674 
677 TF_API
678 std::string
679 TfMakeValidIdentifier(const std::string &in);
680 
685 TF_API
686 std::string TfGetXmlEscapedString(const std::string &in);
687 
689 
690 PXR_NAMESPACE_CLOSE_SCOPE
691 
692 #endif // TF_STRINGUTILS_H
TF_API std::string TfGetXmlEscapedString(const std::string &in)
Escapes characters in in so that they are valid XML.
TF_API std::string TfStringPrintf(const char *fmt,...)
Returns a string formed by a printf()-like specification.
TF_API unsigned long TfStringToULong(const std::string &txt, bool *outOfRange=NULL)
Convert a sequence of digits in txt to an unsigned long value.
std::string TfSafeString(const char *ptr)
Safely create a std::string from a (possibly NULL) char*.
Definition: stringUtils.h:102
bool TfStringEndsWith(const std::string &s, const char *suffix)
Returns true if s ends with suffix.
Definition: stringUtils.h:240
Provides dictionary ordering binary predicate function on strings.
Definition: stringUtils.h:500
TF_API long TfStringToLong(const std::string &txt, bool *outOfRange=NULL)
Convert a sequence of digits in txt to a long int value.
TF_API std::string TfStringGetSuffix(const std::string &name, char delimiter= '.')
Returns the suffix of a string.
TF_API std::vector< std::string > TfStringSplit(std::string const &src, std::string const &separator)
Breaks the given string apart, returning a vector of strings.
TF_API std::string TfStringTrimRight(const std::string &s, const char *trimChars=" \n\t\r")
Trims characters (by default, whitespace) from the right.
bool TfStringStartsWith(const std::string &s, const char *prefix)
Returns true if s starts with prefix.
Definition: stringUtils.h:216
TF_API std::set< std::string > TfStringTokenizeToSet(const std::string &source, const char *delimiters=" \t\n")
Breaks the given string apart, returning a set of strings.
TF_API double TfStringToDouble(const std::string &txt)
Converts text string to double.
TF_API std::string TfStringGlobToRegex(const std::string &s)
Returns a string with glob characters converted to their regular expression equivalents.
TF_API std::string TfMakeValidIdentifier(const std::string &in)
Produce a valid identifier (see TfIsValidIdentifier) from in by replacing invalid characters with &#39;_&#39;...
TF_API std::string TfStringToLower(const std::string &source)
Makes all characters in source lowercase, and returns the result.
TF_API std::string TfStringTrim(const std::string &s, const char *trimChars=" \n\t\r")
Trims characters (by default, whitespace) from the beginning and end of string.
TF_API std::vector< std::string > TfQuotedStringTokenize(const std::string &source, const char *delimiters=" \t\n", std::string *errors=NULL)
Breaks the given quoted string apart, returning a vector of strings.
TF_API std::vector< std::string > TfMatchedStringTokenize(const std::string &source, char openDelimiter, char closeDelimiter, char escapeCharacter= '\0', std::string *errors=NULL)
Breaks the given string apart by matching delimiters.
TF_API bool TfDoubleToString(double d, char *buffer, int len, bool emitTrailingZero)
Writes the string representation of d to buffer of length len.
std::string TfIntToString(int i)
Returns the given integer as a string.
Definition: stringUtils.h:107
A type which offers streaming for floats in a canonical format that can safely roundtrip with the min...
Definition: stringUtils.h:560
static TF_API std::string GetName(TfEnum val)
Returns the name associated with an enumerated value.
Token for efficient comparison, assignment, and hashing of known strings.
Definition: token.h:89
TF_API std::string TfVStringPrintf(const std::string &fmt, va_list ap)
Returns a string formed by a printf()-like specification.
TF_API uint64_t TfStringToUInt64(const std::string &txt, bool *outOfRange=NULL)
Convert a sequence of digits in txt to a uint64_t value.
#define ARCH_PRINTF_FUNCTION(_fmt, _firstArg)
Macro used to indicate a function takes a printf-like specification.
Definition: attributes.h:51
TF_API bool TfStringContains(const std::string &s, const char *substring)
Returns true if s contains substring.
TF_API bool operator()(const std::string &lhs, const std::string &rhs) const
Return true if lhs is less than rhs in dictionary order.
std::string TfStringJoin(ForwardIterator begin, ForwardIterator end, const char *separator=" ")
Concatenates the strings (begin, end), with default separator.
Definition: stringUtils.h:364
TF_API std::string TfStringCapitalize(const std::string &source)
Returns a copy of the source string with only its first character capitalized.
GF_API std::ostream & operator<<(std::ostream &, const GfBBox3d &)
Output a GfBBox3d using the format [(range) matrix zeroArea].
TF_API std::string TfStringToUpper(const std::string &source)
Makes all characters in source uppercase, and returns the result.
TF_API std::string TfStringGetCommonPrefix(std::string a, std::string b)
Returns the common prefix of the input strings, if any.
A type which offers streaming for doubles in a canonical format that can safely roundtrip with the mi...
Definition: stringUtils.h:571
T TfUnstringify(const std::string &instring, bool *status=NULL)
Convert a string to an arbitrary type.
Definition: stringUtils.h:585
TF_API std::string TfGetBaseName(const std::string &fileName)
Returns the base name of a file (final component of the path).
TF_API std::string TfStringGetBeforeSuffix(const std::string &name, char delimiter= '.')
Returns everything up to the suffix of a string.
bool TfIsValidIdentifier(std::string const &identifier)
Test whether identifier is valid.
Definition: stringUtils.h:659
std::enable_if<!std::is_enum< T >::value, std::string >::type TfStringify(const T &v)
Convert an arbitrary type into a string.
Definition: stringUtils.h:523
TF_API std::vector< std::string > TfStringTokenize(const std::string &source, const char *delimiters=" \t\n")
Breaks the given string apart, returning a vector of strings.
TF_API int64_t TfStringToInt64(const std::string &txt, bool *outOfRange=NULL)
Convert a sequence of digits in txt to an int64_t value.
TF_API std::string TfStringReplace(const std::string &source, const std::string &from, const std::string &to)
Replaces all occurrences of string from with to in source.
TF_API std::string TfStringTrimLeft(const std::string &s, const char *trimChars=" \n\t\r")
Trims characters (by default, whitespace) from the left.
TF_API std::string TfStringCatPaths(const std::string &prefix, const std::string &suffix)
Concatenate two strings containing &#39;/&#39; and &#39;..&#39; tokens like a file path or scope name.
TF_API std::string TfEscapeString(const std::string &in)
Process escape sequences in ANSI C string constants.
TF_API std::string TfGetPathName(const std::string &fileName)
Returns the path component of a file (complement of TfGetBaseName()).