#include <iostream>
#include <sstream>
#include <vector>
// 函数用于分割字符串
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 = "C++ is a general-purpose programming language.";
char delimiter = ' ';
std::vector<std::string> words = split(text, delimiter);
// 输出分割后的字符串
for (const auto& word : words) {
std::cout << word << std::endl;
}
return 0;
}
#include <iostream>
: 引入输入输出流库,用于标准输入输出操作。#include <sstream>
: 引入字符串流库,用于从字符串中读取数据。#include <vector>
: 引入向量容器库,用于存储分割后的子字符串。split
函数:str
和一个分隔符 delimiter
。std::istringstream
将字符串转换为字符串流,并通过 std::getline
按照分隔符逐个读取子字符串。std::vector<std::string>
并返回。main
函数:text
。split
函数将字符串按空格分割,并将结果存储在 words
向量中。words
向量并输出每个子字符串。这个示例展示了如何使用 C++ 分割字符串并处理分割后的结果。
上一篇:c++练习
下一篇:c++中&是什么意思
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站