// trim all white space
string str1 = "this is a test str to be trimed! ";
string str2 = " ";
string str3 = "1,2,3,4,5";
auto splitBy = [](string& src, string tar) -> vector<string> {
int st = 0;
vector<string> res;
while (st < src.size()) {
auto pivot = src.find_first_of(tar, st);
if (pivot > src.size()) {
res.push_back(src.substr(st));
return res;
}
res.push_back(src.substr(st, pivot - st));
st = pivot + 1;
}
return res;
};
auto trimSpacesTo1 = [](string& src, string tar) -> string {
// delete leading, tailing
int st = 0;
cout << "dele:" << tar << "|\n";
size_t leadSpace = src.find_first_not_of(" ", 0);
if (leadSpace > src.size()) {
src = "";
return src;
}
src.erase(src.begin(), src.begin() + leadSpace);
size_t tailSpace = src.find_last_not_of(" ");
if (leadSpace > src.size()) {
return src;
}
src.erase(src.begin() + tailSpace + 1, src.end());
while (1) {
size_t nextSt = src.find_first_of(tar, st);
if (nextSt > src.length()) {
break;
}
// from nextSt get space len
size_t nextNotSpace = src.find_first_not_of(tar, nextSt + 1);
if (nextNotSpace - nextSt >= 2) {
src.erase(src.begin() + nextSt, src.begin() + nextNotSpace - 1);
}
st = nextSt + 1;
// src.replace(src.begin() + st, src.begin() + nextSt, "");
}
return src;
};
string tar = " ";
cout << trimSpacesTo1(str1, tar) << "|" << trimSpacesTo1(str2, tar) << "|\n";
auto strToVec = splitBy(str3, ",");
for (auto str : strToVec) {
cout << str << " - ";
}
cout << "\n";
字符的基本处理
最新推荐文章于 2022-12-08 19:17:31 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)