#include <iostream>
#include <vector>
#include <sstream>
// 自定义split函数
std::vector<std::string> split(const std::string& str, char delimiter) {
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(str);
while (std::getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
int main() {
std::string text = "apple,banana,orange";
char delimiter = ',';
std::vector<std::string> result = split(text, delimiter);
for (const auto& s : result) {
std::cout << s << std::endl;
}
return 0;
}
split
函数:这是一个自定义的 split
函数,它接受一个字符串和一个分隔符字符作为参数。该函数使用 std::istringstream
将输入字符串按分隔符分割成多个子字符串,并将这些子字符串存储在一个 std::vector<std::string>
中返回。main
函数:在 main
函数中,我们定义了一个包含逗号分隔的字符串 text
和一个分隔符 delimiter
。然后调用 split
函数进行分割,并将结果存储在 result
向量中。最后,遍历并打印每个分割后的子字符串。这个示例展示了如何在 C++ 中实现类似于 Python 的 split()
方法的功能。
上一篇:c++ 引用和指针的区别
下一篇:c++如何生成随机数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站