在C++中,可以使用std::stringstream
和std::getline
函数按照某个字符对字符串进行分割。以下是一个示例:
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
std::vector<std::string> split(const std::string& s, char delimiter) {
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(s);
while (std::getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
int main() {
std::string str = "hello,world,how,are,you";
char delimiter = ',';
std::vector<std::string> result = split(str, delimiter);
for (const auto& token : result) {
std::cout << token << std::endl;
}
return 0;
}
输出:
hello
world
how
are
you
在这个示例中,我们定义了一个名为split
的函数,它接受一个字符串s
和一个字符delimiter
作为参数。函数使用std::istringstream
和std::getline
按照给定的分隔符将字符串分割成多个子字符串,并将它们存储在一个std::vector<std::string>
中。最后,函数返回这个向量。