我有一个std::sting
这样的:
std::string Str = "PARAM1;PARAM2;PARAM3;PARAM4"
我需要提取每个参数,例如:
char* param1 = explodStr[1] //return PARAM1 ...
我不熟悉 std::string,
谢谢你
我经常将此功能用于此类任务。它就像 PHP 的爆炸一样:
//------------------------------------------------------------------------------
// Name: explode
// Desc: Returns an array of strings, each of which is a substring of <s>
// formed by splitting it on boundaries formed by the string <delimiter>.
// (similar to PHP's explode)
//------------------------------------------------------------------------------
inline std::vector<std::string> explode(const std::string &delimeter, const std::string &s, int limit) {
std::vector<std::string> results;
if(!delimeter.empty()) {
std::string::size_type start = 0;
std::string::size_type end = s.find(delimeter, start);
if(limit <= 0) {
while(end != std::string::npos) {
results.push_back(s.substr(start, end - start));
start = end + delimeter.size();
end = s.find(delimeter, start);
if(start == s.size() && end == std::string::npos) {
results.push_back(std::string());
}
}
} else if(limit > 0) {
while(--limit > 0 && end != std::string::npos) {
results.push_back(s.substr(start, end - start));
start = end + delimeter.size();
end = s.find(delimeter, start);
if(start == s.size() && end == std::string::npos) {
results.push_back(std::string());
}
}
}
if(start != s.size()) {
results.push_back(s.substr(start));
}
while(limit++ < 0 && !results.empty()) {
results.pop_back();
}
}
return results;
}
或者没有限制:
//------------------------------------------------------------------------------
// Name: explode
// Desc: Returns an array of strings, each of which is a substring of <s>
// formed by splitting it on boundaries formed by the string <delimiter>.
// (similar to PHP's explode)
//------------------------------------------------------------------------------
inline std::vector<std::string> explode(const std::string &delimeter, const std::string &s) {
return explode(delimeter, s, 0);
}
用法如下所示:
std::vector<std::string> x = explode(",", "THIS,IS,A,TEST");