strop.cpp 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. //
  2. // Created by xcbosa on 2023/1/31.
  3. //
  4. #include "strop.h"
  5. #include <chrono>
  6. #include <functional>
  7. #include <random>
  8. namespace xc {
  9. namespace utils {
  10. vector<string> split(const string& str, const string& delim) {
  11. vector<string> res;
  12. if ("" == str) return res;
  13. char *strs = new char[str.length() + 1];
  14. strcpy(strs, str.c_str());
  15. char *d = new char[delim.length() + 1];
  16. strcpy(d, delim.c_str());
  17. char *p = strtok(strs, d);
  18. while (p) {
  19. string s = p;
  20. res.push_back(s);
  21. p = strtok(NULL, d);
  22. }
  23. delete[] strs;
  24. delete[] d;
  25. return res;
  26. }
  27. string replace_all(string& src, const string& old_value, const string& new_value) {
  28. for (string::size_type pos(0); pos != string::npos; pos += new_value.length()) {
  29. if ((pos = src.find(old_value, pos)) != string::npos) {
  30. src.replace(pos, old_value.length(), new_value);
  31. }
  32. else break;
  33. }
  34. return src;
  35. }
  36. string fixStringTransfer(string& src) {
  37. string modify = src;
  38. replace_all(modify, "\"", "\\\"");
  39. replace_all(modify, "\r", "\\\r");
  40. replace_all(modify, "\n", "\\\n");
  41. return modify;
  42. }
  43. string& trim(string &s) {
  44. if (s.empty()) { return s; }
  45. s.erase(0,s.find_first_not_of(" "));
  46. s.erase(s.find_last_not_of(" ") + 1);
  47. return s;
  48. }
  49. string uppercase(string s) {
  50. ostringstream oss;
  51. for (char ch : s) {
  52. oss << (char)::toupper(ch);
  53. }
  54. return oss.str();
  55. }
  56. int to_int(string s, bool &isSuccess) {
  57. try {
  58. isSuccess = true;
  59. return stoi(s);
  60. } catch (...) {
  61. isSuccess = false;
  62. }
  63. }
  64. int to_int(string s, int defaultValue) {
  65. try {
  66. return stoi(s);
  67. } catch (...) {
  68. return defaultValue;
  69. }
  70. }
  71. bool is_in(int value, int minIncluded, int maxExcluded) {
  72. return value >= minIncluded && value < maxExcluded;
  73. }
  74. string create_uuid() {
  75. ostringstream stream;
  76. auto random_seed = std::chrono::system_clock::now().time_since_epoch().count();
  77. std::mt19937 seed_engine(random_seed);
  78. std::uniform_int_distribution<std::size_t> random_gen;
  79. std::size_t value = random_gen(seed_engine);
  80. stream << hex << value;
  81. return stream.str();
  82. }
  83. } // xc
  84. } // utils