str_helper.hpp
2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
* @Author: yangzilong
* @Date: 2021-12-01 16:47:49
* @Last Modified by: yangzilong
* @Last Modified time: Do not edit
* @Email: yangzilong@objecteye.com
* @Description:
*/
#pragma once
#include <vector>
#include <cstring>
#include <sstream>
namespace helpers
{
namespace string
{
std::vector<std::string> split_string(const std::string &str, char delim)
{
std::stringstream ss(str);
std::string item;
std::vector<std::string> elems;
while (std::getline(ss, item, delim))
elems.emplace_back(std::move(item));
return std::move(elems);
}
template<typename Dtype = std::string>
std::string join_string(const std::vector<Dtype> &vec, const std::string &join_str)
{
auto to_string_func = [](Dtype &val)
{
std::string it = "";
if (std::is_same<std::string, decltype(val)>::value)
it = val;
else
it = std::to_string(val); // simple transfer...
return it;
};
std::string res = "";
for (Dtype val: vec)
res.append(to_string_func(val) + join_str);
return res.substr(0, res.length() - join_str.length());
}
std::string replace(const std::string &src, const std::string &replace_src, const std::string &replace_dst)
{
std::string src_copied = src;
auto find_result = src_copied.find(replace_src);
if (find_result != std::string::npos)
src_copied.replace(find_result, replace_src.length(), replace_dst);
return src_copied;
}
std::string replace_all(const std::string &src, const std::string &replace_src, const std::string &replace_dst)
{
std::string src_copied = src;
while (true)
{
std::string src_temp = src_copied;
if (src_temp == (src_copied = replace(src_copied, replace_src, replace_dst)))
break;
}
return src_copied;
}
} // namespace string
} // namespace helper