StringHelpers.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include "StringHelpers.h"
  9. #include "Util.h"
  10. #include <cwctype>
  11. int StringHelpers::CompareIgnoreCase(const AZStd::string& str0, const AZStd::string& str1)
  12. {
  13. const size_t minLength = Util::getMin(str0.length(), str1.length());
  14. const int result = azstrnicmp(str0.c_str(), str1.c_str(), minLength);
  15. if (result)
  16. {
  17. return result;
  18. }
  19. else
  20. {
  21. return (str0.length() == str1.length())
  22. ? 0
  23. : ((str0.length() < str1.length()) ? -1 : +1);
  24. }
  25. }
  26. int StringHelpers::CompareIgnoreCase(const AZStd::wstring& str0, const AZStd::wstring& str1)
  27. {
  28. const size_t minLength = Util::getMin(str0.length(), str1.length());
  29. for (size_t i = 0; i < minLength; ++i)
  30. {
  31. const wchar_t c0 = towlower(str0[i]);
  32. const wchar_t c1 = towlower(str1[i]);
  33. if (c0 != c1)
  34. {
  35. return (c0 < c1) ? -1 : 1;
  36. }
  37. }
  38. return (str0.length() == str1.length())
  39. ? 0
  40. : ((str0.length() < str1.length()) ? -1 : +1);
  41. }
  42. template <class TS>
  43. static inline void Split_Tpl(const TS& str, const TS& separator, bool bReturnEmptyPartsToo, std::vector<TS>& outParts)
  44. {
  45. if (str.empty())
  46. {
  47. return;
  48. }
  49. if (separator.empty())
  50. {
  51. for (size_t i = 0; i < str.length(); ++i)
  52. {
  53. outParts.push_back(str.substr(i, 1));
  54. }
  55. return;
  56. }
  57. size_t partStart = 0;
  58. for (;; )
  59. {
  60. const size_t pos = str.find(separator, partStart);
  61. if (pos == TS::npos)
  62. {
  63. break;
  64. }
  65. if (bReturnEmptyPartsToo || (pos > partStart))
  66. {
  67. outParts.push_back(str.substr(partStart, pos - partStart));
  68. }
  69. partStart = pos + separator.length();
  70. }
  71. if (bReturnEmptyPartsToo || (partStart < str.length()))
  72. {
  73. outParts.push_back(str.substr(partStart, str.length() - partStart));
  74. }
  75. }
  76. void StringHelpers::Split(const AZStd::string& str, const AZStd::string& separator, bool bReturnEmptyPartsToo, std::vector<AZStd::string>& outParts)
  77. {
  78. Split_Tpl(str, separator, bReturnEmptyPartsToo, outParts);
  79. }
  80. void StringHelpers::Split(const AZStd::wstring& str, const AZStd::wstring& separator, bool bReturnEmptyPartsToo, std::vector<AZStd::wstring>& outParts)
  81. {
  82. Split_Tpl(str, separator, bReturnEmptyPartsToo, outParts);
  83. }