#include <iostream>
#include <sstream>
#include <vector>
// Function to split a string by a delimiter and return a vector of substrings
std::vector<std::string> split(const std::string& str, char delimiter) {
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(str);
// Extract words from the stream one by one using the delimiter
while (std::getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
int main() {
std::string text = "Hello,world,this,is,a,test";
char delimiter = ',';
// Call the split function and store the result in a vector
std::vector<std::string> words = split(text, delimiter);
// Print each word in the vector
for (const auto& word : words) {
std::cout << word << std::endl;
}
return 0;
}
split
函数:这个函数接受一个字符串 str
和一个分隔符 delimiter
,然后使用 std::istringstream
将字符串按分隔符分割成多个子字符串,并将这些子字符串存储在一个 std::vector<std::string>
中返回。main
函数:在 main
函数中,定义了一个包含逗号分隔的字符串 text
和分隔符 delimiter
。调用 split
函数后,结果存储在 words
向量中,最后通过循环输出每个子字符串。这段代码展示了如何在 C++ 中实现简单的字符串分割功能。
上一篇:智能指针c++11
下一篇:c++浮点数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站