C++字符串切割

字符串切割

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <algorithm>
#include <string>
#include <vector>

void StringUtils::SplitString(const std::string& source, const std::string& delimiter, std::vector<std::string>& vec) {
size_t last = 0;
size_t index = source.find_first_of(delimiter);
while (index != std::string::npos) {
vec.push_back(source.substr(last, index - last));
last = index + 1;
index = source.find_first_of(delimiter, last);
}

if (std::string::npos == index) {
std::string strTmp = source.substr(last, source.length() - last);
if (!strTmp.empty()) {
vec.push_back(strTmp);
}
}
}

字符串切割并删除空格

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
#include <algorithm>
#include <string>
#include <vector>

void StringUtils::SplitStringWithTrim(const std::string& source,
const std::string& delimiter,
std::vector<std::string>& vec) {
size_t last = 0;
size_t index = source.find_first_of(delimiter);
while (index != std::string::npos) {
std::string strTmp = source.substr(last, index - last);
vec.push_back(trim(strTmp));
last = index + 1;
index = source.find_first_of(delimiter, last);
}

if (std::string::npos == index) {
std::string strTmp = source.substr(last, source.length() - last);
if (!strTmp.empty()) {
vec.push_back(trim(strTmp));
}
}
}

// trim from begin
static inline std::string& ltrim(std::string& s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
return s;
}

// trim from end
static inline std::string& rtrim(std::string& s) {
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}

// trim from both ends
static inline std::string& trim(std::string& s) { return ltrim(rtrim(s)); }

C++字符串切割
http://example.com/2024/03/28/C-字符串切割/
作者
Liu XinWei
发布于
2024年3月28日
许可协议