mirror of
https://github.com/lifegpc/c-utils.git
synced 2026-06-11 15:58:49 +08:00
add more functions
This commit is contained in:
28
str_util.cpp
28
str_util.cpp
@@ -30,22 +30,33 @@ std::string str_util::str_replace(std::string input, std::string pattern, std::s
|
||||
return input;
|
||||
}
|
||||
|
||||
std::list<std::string> str_util::str_split(std::string input, std::string pattern, size_t max) {
|
||||
std::list<std::string> str_util::str_split(std::string input, std::string pattern, size_t max, bool break_quote) {
|
||||
if (max == 0) return {};
|
||||
std::list<std::string> li;
|
||||
auto loc = input.find(pattern, 0);
|
||||
auto last_loc = 0;
|
||||
auto pre_loc = 0;
|
||||
auto len = pattern.length();
|
||||
while (loc != -1 && li.size() < max) {
|
||||
li.push_back(input.substr(last_loc, loc - last_loc));
|
||||
auto s = input.substr(pre_loc, loc - pre_loc);
|
||||
if (break_quote || (s.front() != '"' && s.front() != '\'') || s.back() == s.front()) {
|
||||
li.push_back(s);
|
||||
pre_loc = loc + len;
|
||||
}
|
||||
last_loc = loc + len;
|
||||
if (last_loc < input.length()) loc = input.find(pattern, max(0, last_loc));
|
||||
else break;
|
||||
}
|
||||
if (last_loc <= input.length()) li.push_back(input.substr(last_loc, input.length() - last_loc));
|
||||
if (last_loc <= input.length()) li.push_back(input.substr(pre_loc, input.length() - pre_loc));
|
||||
return li;
|
||||
}
|
||||
|
||||
std::vector<std::string> str_util::str_splitv(std::string input, std::string pattern, size_t max, bool break_quote) {
|
||||
auto list = str_split(input, pattern, max, break_quote);
|
||||
std::vector<std::string> vec(list.begin(), list.end());
|
||||
return vec;
|
||||
}
|
||||
|
||||
std::string str_util::str_hex(std::string input) {
|
||||
if (input.empty()) return "";
|
||||
const char* t = "0123456789abcdef";
|
||||
@@ -65,3 +76,14 @@ bool str_util::str_endswith(std::string input, std::string pattern) {
|
||||
auto i = input.rfind(pattern);
|
||||
return i == ilen - plen;
|
||||
}
|
||||
|
||||
std::string str_util::remove_quote(std::string input) {
|
||||
if (input.length() < 2) return input;
|
||||
if (input[0] == '"' && input[input.length() - 1] == '"') {
|
||||
return input.substr(1, input.length() - 2);
|
||||
} else if (input[0] == '\'' && input[input.length() - 1] == '\'') {
|
||||
return input.substr(1, input.length() - 2);
|
||||
} else {
|
||||
return input;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user