stringstream可高效分割字符串,示例用>>提取空白分隔内容,或getline配合自定义分隔符如逗号,支持过滤空项,适用于解析CSV等场景,需注意clear重置状态。

在C++中,使用stringstream是一种常见且高效的方式处理字符串分割。它能自动按空白字符(空格、换行、制表符)拆分字符串,并支持逐个提取子串。这种方法不需要引入额外库,代码简洁易懂。
stringstream是C++标准库中的一个类,定义在
通过操作符,可以从stringstream中依次提取以空白符分隔的内容。
示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
int main() {
std::string str = "apple banana cherry";
std::stringstream ss(str);
std::string word;
std::vector<std::string> result;
while (ss >> word) {
result.push_back(word);
}
for (const auto& w : result) {
std::cout << w << std::endl;
}
return 0;
}
输出结果为每行一个单词:
apple默认情况下,stringstream以空白字符作为分隔符。如果需要使用其他分隔符(如逗号、分号等),可以通过getline()函数配合指定的分隔符实现。
例如,分割以逗号分隔的字符串:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
int main() {
std::string str = "apple,banana,cherry";
std::stringstream ss(str);
std::string item;
std::vector<std::string> result;
while (std::getline(ss, item, ',')) {
result.push_back(item);
}
for (const auto& elem : result) {
std::cout << elem << std::endl;
}
return 0;
}
这里std::getline(ss, item, ',')表示从ss中读取字符直到遇到逗号,然后把前面的内容存入item。
当字符串中存在连续分隔符时(如"apple,,cherry"),默认行为会保留空字符串。若希望跳过空项,可添加判断:
while (std::getline(ss, item, ',')) {
if (!item.empty()) {
result.push_back(item);
}
}
这样可以过滤掉因连续分隔符产生的空字符串。
这种分割方式适用于解析配置项、CSV数据、命令行参数等场景。优点是语法简单,兼容标准C++;缺点是对复杂分隔规则(如多字符分隔符)支持有限。
注意:每次使用同一个stringstream对象处理新字符串前,需调用.clear()重置状态,避免读取失败。
ss.clear(); // 清除错误标志 ss.str(new_str); // 设置新字符串
基本上就这些。stringstream结合getline是C++中最实用的字符串分割技巧之一,不复杂但容易忽略细节。掌握它能有效提升文本处理效率。
以上就是C++如何实现字符串分割_C++ stringstream流处理分割字符串的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号