c++怎么拆分字符串

655Z技术栈 C/C++编程 2026年01月31日 10

在C++中,可以使用以下几种方法来拆分字符串:

  1. 使用stringstream类:可以使用stringstream类来将字符串按照指定的分隔符拆分成多个子字符串。
#include <iostream> #include <sstream> #include <vector> int main() { std::string str = "Hello,world,this,is,a,test"; std::stringstream ss(str); std::vector<std::string> tokens; std::string token; while (std::getline(ss, token, ',')) { tokens.push_back(token); } for (const auto &t : tokens) { std::cout << t << std::endl; } return 0; }
  1. 使用find和substr方法:可以使用find和substr方法来找到分隔符位置并截取子字符串。
#include <iostream> #include <vector> int main() { std::string str = "Hello,world,this,is,a,test"; std::string delimiter = ","; std::vector<std::string> 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 << std::endl; } return 0; }

这些方法可以根据具体的需求选择合适的方式来拆分字符串。

提供PHP及ThinkPHP框架的定制开发、代码优化,PHP修改、ThinkPHP修改。

邮箱:yvsm@163.com 微信:yvsm316 QQ:316430983
关闭

用微信“扫一扫”