StringUtil.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. #include "StringUtil.h"
  2. #include <string>
  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 equals(const std::string& a, const char* b)
  69. {
  70. return (a.compare(b) == 0);
  71. }
  72. bool equalsIgnoreCase(const std::string& a, const char* b)
  73. {
  74. size_t bLength = strlen(b);
  75. if (a.size() != bLength)
  76. {
  77. return false;
  78. }
  79. for (size_t i = 0; i < bLength; i++)
  80. {
  81. if (lowercase(a[i]) != lowercase(b[i]))
  82. {
  83. return false;
  84. }
  85. }
  86. return true;
  87. }
  88. }