StringTools.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <Jolt/Jolt.h>
  4. #include <Jolt/Core/StringTools.h>
  5. #include <cstdarg>
  6. namespace JPH {
  7. string StringFormat(const char *inFMT, ...)
  8. {
  9. static char buffer[1024];
  10. // Format the string
  11. va_list list;
  12. va_start(list, inFMT);
  13. vsnprintf(buffer, sizeof(buffer), inFMT, list);
  14. return string(buffer);
  15. }
  16. void StringReplace(string &ioString, string inSearch, string inReplace)
  17. {
  18. size_t index = 0;
  19. for (;;)
  20. {
  21. index = ioString.find(inSearch, index);
  22. if (index == std::string::npos)
  23. break;
  24. ioString.replace(index, inSearch.size(), inReplace);
  25. index += inReplace.size();
  26. }
  27. }
  28. void StringToVector(const string &inString, vector<string> &outVector, const string &inDelimiter, bool inClearVector)
  29. {
  30. JPH_ASSERT(inDelimiter.size() > 0);
  31. // Ensure vector empty
  32. if (inClearVector)
  33. outVector.clear();
  34. // No string? no elements
  35. if (inString.empty())
  36. return;
  37. // Start with initial string
  38. string s(inString);
  39. // Add to vector while we have a delimiter
  40. size_t i;
  41. while (!s.empty() && (i = s.find(inDelimiter)) != string::npos)
  42. {
  43. outVector.push_back(s.substr(0, i));
  44. s.erase(0, i + inDelimiter.length());
  45. }
  46. // Add final element
  47. outVector.push_back(s);
  48. }
  49. void VectorToString(const vector<string> &inVector, string &outString, const string &inDelimiter)
  50. {
  51. // Ensure string empty
  52. outString.clear();
  53. for (vector<string>::const_iterator i = inVector.begin(); i != inVector.end(); ++i)
  54. {
  55. // Add delimiter if not first element
  56. if (!outString.empty())
  57. outString.append(inDelimiter);
  58. // Add element
  59. outString.append(*i);
  60. }
  61. }
  62. string ToLower(const string &inString)
  63. {
  64. string out;
  65. out.reserve(inString.length());
  66. for (char c : inString)
  67. out.push_back((char)tolower(c));
  68. return out;
  69. }
  70. const char *NibbleToBinary(uint32 inNibble)
  71. {
  72. static const char *nibbles[] = { "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111" };
  73. return nibbles[inNibble & 0xf];
  74. }
  75. } // JPH