StringUtil.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. #include "Base.h"
  2. #include "StringUtil.h"
  3. namespace gameplay
  4. {
  5. inline char lowercase(char c)
  6. {
  7. if (c >= 'A' && c <='Z')
  8. {
  9. c |= 0x20;
  10. }
  11. return c;
  12. }
  13. bool startsWith(const char* str, const char* prefix, bool ignoreCase)
  14. {
  15. size_t length = strlen(str);
  16. size_t prefixLength = strlen(prefix);
  17. if (prefixLength > length)
  18. {
  19. return false;
  20. }
  21. const char* p = str;
  22. while (*p != '\0' && *prefix != '\0')
  23. {
  24. if (ignoreCase)
  25. {
  26. if (lowercase(*p) != lowercase(*prefix))
  27. {
  28. return false;
  29. }
  30. }
  31. else if (*p != *prefix)
  32. {
  33. return false;
  34. }
  35. ++p;
  36. ++prefix;
  37. }
  38. return true;
  39. }
  40. bool endsWith(const char* str, const char* suffix, bool ignoreCase)
  41. {
  42. size_t length = strlen(str);
  43. size_t suffixLength = strlen(suffix);
  44. if (suffixLength > length)
  45. {
  46. return false;
  47. }
  48. size_t offset = length - suffixLength;
  49. const char* p = str + offset;
  50. while (*p != '\0' && *suffix != '\0')
  51. {
  52. if (ignoreCase)
  53. {
  54. if (lowercase(*p) != lowercase(*suffix))
  55. {
  56. return false;
  57. }
  58. }
  59. else if (*p != *suffix)
  60. {
  61. return false;
  62. }
  63. ++p;
  64. ++suffix;
  65. }
  66. return true;
  67. }
  68. bool endsWith(const std::string& str, const char* suffix, bool ignoreCase)
  69. {
  70. return endsWith(str.c_str(), suffix, ignoreCase);
  71. }
  72. bool equals(const std::string& a, const char* b)
  73. {
  74. return (a.compare(b) == 0);
  75. }
  76. bool equals(const std::string& a, const std::string& b)
  77. {
  78. return (a.compare(b) == 0);
  79. }
  80. bool equalsIgnoreCase(const std::string& a, const char* b)
  81. {
  82. size_t bLength = strlen(b);
  83. if (a.size() != bLength)
  84. {
  85. return false;
  86. }
  87. for (size_t i = 0; i < bLength; ++i)
  88. {
  89. if (lowercase(a[i]) != lowercase(b[i]))
  90. {
  91. return false;
  92. }
  93. }
  94. return true;
  95. }
  96. std::string getFilenameFromFilePath(const std::string& filepath)
  97. {
  98. if (filepath.find_last_of("/") != std::string::npos)
  99. {
  100. return filepath.substr(filepath.find_last_of("/") + 1);
  101. }
  102. return "";
  103. }
  104. std::string getFilenameNoExt(const std::string& filename)
  105. {
  106. if (filename.find_last_of(".") != std::string::npos)
  107. {
  108. return filename.substr(0, filename.find_last_of("."));
  109. }
  110. return filename;
  111. }
  112. }