I have a std::sting
like that:
std::string Str = "PARAM1;PARAM2;PARAM3;PARAM4"
and I need to extract each parameters like:
char* param1 = explodStr[1] //return PARAM1 ...
I'm not familiar with std::string,
thank you
I have a std::sting
like that:
std::string Str = "PARAM1;PARAM2;PARAM3;PARAM4"
and I need to extract each parameters like:
char* param1 = explodStr[1] //return PARAM1 ...
I'm not familiar with std::string,
thank you
I often use this function for this type of task. It acts like PHP's explode:
//------------------------------------------------------------------------------
// 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;
}
Or with no limit:
//------------------------------------------------------------------------------
// 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);
}
Usage looks like this:
std::vector<std::string> x = explode(",", "THIS,IS,A,TEST");