答案:C++中可通过std::getline实现单字符分割,结合std::stringstream和vector处理空值;对于多字符分隔符则使用find与substr组合,灵活支持子串分割并按需过滤空结果。

在 C++ 中,标准库没有提供像 Python 的 split() 那样直接的字符串分割函数,但我们可以借助 std::stringstream、std::getline 和容器(如 std::vector)来实现灵活的字符串分割功能。下面介绍几种常用方法,并给出完整示例。
这是最常见且简洁的方法,适用于单字符分隔符(如空格、逗号、分号等)。
// 示例:按逗号分割字符串#include <iostream>
#include <string>
#include <sstream>
#include <vector>
std::vector<std::string> split(const std::string& str, char delim) {
std::vector<std::string> result;
std::stringstream ss(str);
std::string item;
while (std::getline(ss, item, delim)) {
result.push_back(item);
}
return result;
}
int main() {
std::string input = "apple,banana,orange";
auto parts = split(input, ',');
for (const auto& part : parts) {
std::cout << part << std::endl;
}
return 0;
}
输出:
apple
banana
orange
当输入中可能包含连续分隔符(如 "a,,b")时,getline 会返回空字符串。可添加过滤逻辑跳过空项。
立即学习“C++免费学习笔记(深入)”;
// 修改后的 split 函数,忽略空结果std::vector<std::string> splitSkipEmpty(const std::string& str, char delim) {
std::vector<std::string> result;
std::stringstream ss(str);
std::string item;
while (std::getline(ss, item, delim)) {
if (!item.empty()) {
result.push_back(item);
}
}
return result;
}
例如,输入 "hello,,,world" 将只返回 "hello" 和 "world"。
这种方法更灵活,支持多字符分隔符(子串),适合复杂场景。
// 按子串分割std::vector<std::string> splitByString(const std::string& str, const std::string& delimiter) {
std::vector<std::string> result;
size_t start = 0;
size_t end = str.find(delimiter);
while (end != std::string::npos) {
result.push_back(str.substr(start, end - start));
start = end + delimiter.length();
end = str.find(delimiter, start);
}
result.push_back(str.substr(start));
return result;
}
// 使用示例
std::string text = "one||two||three";
auto parts = splitByString(text, "||");
对于单字符分隔,推荐使用 std::getline 方法,简单高效。
需要处理多字符分隔符时,使用 find + substr 更合适。
注意根据需求决定是否保留空字符串。
基本上就这些,不复杂但容易忽略细节。
以上就是C++ 如何分割字符串_C++ 字符串分割函数实现与示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号