首页 > 解决方案 > 使用字符分隔符在 C++ 中解析字符串,但在每个解析的子字符串中保留可重复的字符作为分隔符(C++ STL)

问题描述

我怎样才能解析这个字符串:

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

像这样进入向量:

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

仅使用 C++ STL?

标签: c++stringparsing

解决方案


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

一个可能的代码可能是:

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


推荐阅读