方式一
#include <string>
#include <vector>
#include <sstream>
#include <iostream>
std::vector<std::string> split(const std::string& str, char delim) {
std::stringstream ss(str);
std::string item;
std::vector<std::string> elems;
while (std::getline(ss, item, delim))
{
if (!item.empty())
{
elems.push_back(item);
}
}
return elems;
}
int main()
{
std::string str = "CSDN CaosShangPa";
std::vector<std::string> subStrs = split(str, ' ');
for (const auto &subStr : subStrs)
{
std::cout << subStr << std::endl;
}
return 0;
}
方式二
#include <string>
#include <vector>
#include <regex>
#include <iostream>
std::vector<std::string> split(const std::string& str, char delim) {
std::string s;
s.append(1, delim);
std::regex reg(s);
std::vector<std::string> elems(std::sregex_token_iterator(str.begin(), str.end(), reg, -1),
std::sregex_token_iterator());
return elems;
}
int main()
{
std::string str = "CSDN CaosShangPa";
std::vector<std::string> subStrs = split(str, ' ');
for (const auto &subStr : subStrs)
{
std::cout << subStr << std::endl;
}
return 0;
}
原文链接:C++之分割字符串的两种方式-CSDN博客