C++:编写一个分割字符串的函数
在 C++ 程序中,经常需要对字符串进行操作,例如分割字符串。为了方便实现这个功能,我们可以编写一个分割字符串的函数。下面是一个示例代码:
#include <iostream>
#include <string>
#include <vector>
std::vector<std::string> split(std::string str, const std::string& delimiter) {
std::vector<std::string> result;
size_t pos = 0;
std::string token;
while ((pos = str.find(delimiter)) != std::string::npos) {
token = str.substr(0, pos);
result.push_back(token);
str.erase(0, pos + delimiter.length());
}
result.push_back(str);
return result;
}
int main() {
std::string str = "apple,banana,orange";
std::vector<std::string> result = split(str,