阅读量:119
在C++中,可以使用以下几种方法来拆分字符串:
- 使用stringstream类:可以使用stringstream类来将字符串按照指定的分隔符拆分成多个子字符串。
#include
#include
#include
int main() {
std::string str = "Hello,world,this,is,a,test";
std::stringstream ss(str);
std::vector tokens;
std::string token;
while (std::getline(ss, token, ',')) {
tokens.push_back(token);
}
for (const auto &t : tokens) {
std::cout << t class="hljs-keyword">return 0;
}
- 使用find和substr方法:可以使用find和substr方法来找到分隔符位置并截取子字符串。
#include
#include
int main() {
std::string str = "Hello,world,this,is,a,test";
std::string delimiter = ",";
std::vector tokens;
size_t pos = 0;
std::string token;
while ((pos = str.find(delimiter)) != std::string::npos) {
token = str.substr(0, pos);
tokens.push_back(token);
str.erase(0, pos + delimiter.length());
}
tokens.push_back(str);
for (const auto &t : tokens) {
std::cout << t class="hljs-keyword">return 0;
}
这些方法可以根据具体的需求选择合适的方式来拆分字符串。