utils.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #include "utils.h"
  2. #include <algorithm>
  3. #include <regex>
  4. bool replace(std::string &str, const std::string &from, const std::string &to) {
  5. size_t start_pos = str.find(from);
  6. if (start_pos == std::string::npos)
  7. return false;
  8. str.replace(start_pos, from.length(), to);
  9. return true;
  10. }
  11. bool replace(std::string &str, const char *from, const char *to) {
  12. size_t start_pos = str.find(from);
  13. if (start_pos == std::string::npos)
  14. return false;
  15. str.replace(start_pos, strlen(from), to);
  16. return true;
  17. }
  18. bool file_exists(const std::string &name) {
  19. std::ifstream f(name.c_str());
  20. return f.good();
  21. }
  22. bool file_exists(const char *name) {
  23. std::ifstream f(name);
  24. return f.good();
  25. }
  26. void string_toupper(std::string &str) {
  27. std::transform(str.begin(), str.end(), str.begin(), ::toupper);
  28. }
  29. /**
  30. * @brief Case Insensitive std::string compare
  31. *
  32. * @param a
  33. * @param b
  34. * @return true
  35. * @return false
  36. */
  37. bool iequals(const std::string &a, const std::string &b) {
  38. unsigned int sz = a.size();
  39. if (b.size() != sz)
  40. return false;
  41. for (unsigned int i = 0; i < sz; ++i)
  42. if (std::tolower(a[i]) != std::tolower(b[i]))
  43. return false;
  44. return true;
  45. }
  46. std::vector<std::pair<int, int>> find_words(const std::string &text) {
  47. std::vector<std::pair<int, int>> words;
  48. // this is expensive to construct, so only construct it once.
  49. static std::regex word("([a-zA-Z]+)");
  50. for (auto it = std::sregex_iterator(text.begin(), text.end(), word);
  51. it != std::sregex_iterator(); ++it) {
  52. words.push_back(std::make_pair(it->position(), it->length()));
  53. }
  54. return words;
  55. }
  56. // From: https://stackoverflow.com/questions/236129/how-do-i-iterate-over-the-words-of-a-string
  57. std::vector<std::string> split(const std::string &text, char sep) {
  58. std::vector<std::string> tokens;
  59. std::size_t start = 0, end = 0;
  60. while ((end = text.find(sep, start)) != std::string::npos) {
  61. if (end != start) {
  62. tokens.push_back(text.substr(start, end - start));
  63. }
  64. start = end + 1;
  65. }
  66. if (end != start) {
  67. tokens.push_back(text.substr(start));
  68. }
  69. return tokens;
  70. }