使用 char 分隔符解析C++中的字符串,但将可重复的字符保留为每个解析的子字符串 (C++ STL) 中的分隔符

Parse a string in C++ using char delimiter but keep repeatable chars as delimiter inside each parsed substring (C++ STL)

本文关键字:字符串 C++ 分隔符 保留 STL char 使用 字符      更新时间:2023-10-16

如何解析这个字符串:

std::string input_str = "-10-20--300---400";

像这样进入矢量:

std::vector<string> output = { "-10", "20", "-300", "--400" };

仅使用 C++ STL?

这里的问题是您希望保留(可能多个(分隔符及其字符串。由于我懒得手动实现标准库中已经存在的内容,并且由于 C 标准库明确包含在C++库中,因此我将使用strspnstrcspn函数来分隔子字符串的起点和终点并将它们复制到向量。

可能的代码可以是:

#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没有发出警告......