c++ - 使用字符分隔符在 C++ 中解析字符串,但在每个解析的子字符串中保留可重复的字符作为分隔符(C++ STL)
问题描述
我怎样才能解析这个字符串:
std::string input_str = "-10-20--300---400";
像这样进入向量:
std::vector<string> output = { "-10", "20", "-300", "--400" };
仅使用 C++ STL?
解决方案
这里的问题是您希望将(可能是多个)分隔符与其字符串一起保留。由于我懒得手动实现标准库中已经存在的内容,并且由于 C 标准库明确包含在 C++ 中,我将使用strspn
andstrcspn
函数来分隔子字符串的起点和终点并复制它们到一个向量。
一个可能的代码可能是:
#include <string>
#include <vector>
#include <cstring>
std::vector<std::string> parse(std::string input_str) {
static const char delim[] = "-";
std::vector<std::string> resul;
const char *ix = input_str.c_str();
const char *sentinel = ix + input_str.size();
while (ix < sentinel) {
const char *end = ix + strspn(ix, delim); // end of delim sequence
if (end < sentinel) { // stop at end of string!
end = end + strcspn(end, delim); // go to next sequence
}
resul.insert(resul.end(), std::string(ix, end-ix));
ix = end;
if (ix < sentinel) ix += 1; // skip delimiter if not at end of string
}
return resul;
}
它给出了预期的向量,并将字符串的复制和分配限制在最低限度。也许相当 C-ish 但应该是正确的 C++ 和 Clang 没有发出警告......
推荐阅读
- wordpress - Woocommerce:如何在管理订单页面中将自定义可靠数量添加到订单总额?
- c# - 无法使用 Autofac 注入对象
- javascript - 嵌套中继器 - 子中继器价格添加复选框单击父中继器价格
- r - 按日期范围和 ID 连接,面板数据
- arcore - ARCore 是否与 Android Instant Apps 兼容?
- javascript - 如何防止 Cloud Firestore 拆分地图键?
- linux - 什么是“内核堆栈”?
- swift - 如何查看哪个tableView在顶部
- spring-boot - springboot2 +webflux + websocket
- javascript - 当我尝试使用“$inc”运算符增加 MongoDB 数据库中的年龄参数时出现“未处理的承诺拒绝警告”