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 PXR_BASE_TF_STRING_UTILS_H
25 #define PXR_BASE_TF_STRING_UTILS_H
26 
30 
31 #include "pxr/pxr.h"
32 
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 
427 TF_API
428 std::vector<std::string> TfStringTokenize(const std::string& source,
429  const char* delimiters = " \t\n");
430 
434 TF_API
435 std::set<std::string> TfStringTokenizeToSet(const std::string& source,
436  const char* delimiters = " \t\n");
437 
447 TF_API
448 std::vector<std::string>
449 TfQuotedStringTokenize(const std::string& source,
450  const char* delimiters = " \t\n",
451  std::string *errors = NULL);
452 
463 TF_API
464 std::vector<std::string>
465 TfMatchedStringTokenize(const std::string& source,
466  char openDelimiter,
467  char closeDelimiter,
468  char escapeCharacter = '\0',
469  std::string *errors = NULL);
470 
477 inline
478 std::vector<std::string>
479 TfMatchedStringTokenize(const std::string& source,
480  char openDelimiter,
481  char closeDelimiter,
482  std::string *errors)
483 {
484  return TfMatchedStringTokenize(source, openDelimiter,
485  closeDelimiter, '\0', errors);
486 }
487 
517  TF_API bool operator()(const std::string &lhs, const std::string &rhs) const;
518 };
519 
525 template <typename T>
526 typename std::enable_if<!std::is_enum<T>::value, std::string>::type
527 TfStringify(const T& v)
528 {
529  std::ostringstream stream;
530  stream << v;
531  return stream.str();
532 }
533 
535 template <typename T>
536 typename std::enable_if<std::is_enum<T>::value, std::string>::type
537 TfStringify(const T& v)
538 {
539  return TfEnum::GetName(v);
540 }
541 
543 TF_API std::string TfStringify(bool v);
545 TF_API std::string TfStringify(std::string const&);
547 TF_API std::string TfStringify(float);
549 TF_API std::string TfStringify(double);
550 
557 TF_API bool TfDoubleToString(
558  double d, char* buffer, int len, bool emitTrailingZero);
559 
565  explicit TfStreamFloat(float f) : value(f) {}
566  float value;
567 };
568 
569 TF_API std::ostream& operator<<(std::ostream& o, TfStreamFloat t);
570 
576  explicit TfStreamDouble(double d) : value(d) {}
577  double value;
578 };
579 
580 TF_API std::ostream& operator<<(std::ostream& o, TfStreamDouble t);
581 
587 template <typename T>
588 T
589 TfUnstringify(const std::string &instring, bool* status = NULL)
590 {
591  T v = T();
592  std::istringstream stream(instring);
593  stream >> v;
594  if (status && !stream)
595  *status = false;
596  return v;
597 }
598 
600 template <>
601 TF_API
602 bool TfUnstringify(const std::string &instring, bool* status);
604 template <>
605 TF_API
606 std::string TfUnstringify(const std::string &instring, bool* status);
607 
613 TF_API
614 std::string TfStringGlobToRegex(const std::string& s);
615 
642 //
647 TF_API std::string TfEscapeString(const std::string &in);
648 TF_API void TfEscapeStringReplaceChar(const char** in, char** out);
649 
660 TF_API
661 std::string TfStringCatPaths( const std::string &prefix,
662  const std::string &suffix );
663 
669 inline bool
670 TfIsValidIdentifier(std::string const &identifier)
671 {
672  char const *p = identifier.c_str();
673  auto letter = [](unsigned c) { return ((c-'A') < 26) || ((c-'a') < 26); };
674  auto number = [](unsigned c) { return (c-'0') < 10; };
675  auto under = [](unsigned c) { return c == '_'; };
676  unsigned x = *p;
677  if (!x || number(x)) {
678  return false;
679  }
680  while (letter(x) || number(x) || under(x)) {
681  x = *p++;
682  };
683  return x == 0;
684 }
685 
688 TF_API
689 std::string
690 TfMakeValidIdentifier(const std::string &in);
691 
696 TF_API
697 std::string TfGetXmlEscapedString(const std::string &in);
698 
700 
701 PXR_NAMESPACE_CLOSE_SCOPE
702 
703 #endif // PXR_BASE_TF_STRING_UTILS_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:504
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.
Define function attributes.
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:564
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:87
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.
Define integral types.
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:575
T TfUnstringify(const std::string &instring, bool *status=NULL)
Convert a string to an arbitrary type.
Definition: stringUtils.h:589
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:670
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:527
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()).