在 C++ 中解析逗号分隔的整数/整数范围

Efr*_*shp 3 c++ string parsing split

给定 C++ 中的字符串,其中包含以下类型的范围和单个数字:

"2,3,4,7-9"
Run Code Online (Sandbox Code Playgroud)

我想将其解析为以下形式的向量:

2,3,4,7,8,9
Run Code Online (Sandbox Code Playgroud)

如果数字由 a 分隔,-那么我想推送该范围内的所有数字。否则我想推送一个数字。

我尝试使用这段代码:

"2,3,4,7-9"
Run Code Online (Sandbox Code Playgroud)

问题是它不适用于范围。它只取字符串中的数字,而不是范围内的所有数字。

Jan*_*tke 5

您的问题由两个独立的问题组成:

  1. 将字符串拆分为多个字符串 ,
  2. 解析每个字符串时将数字或数字范围添加到向量

如果您首先在逗号处拆分整个字符串,则不必担心同时在连字符处拆分它。这就是你所说的分而治之的方法。

拆分于 ,

这个问题应该告诉你如何用逗号分割字符串。

解析并添加到 std::vector<int>

将字符串拆分为逗号后,您只需要通过为每个字符串调用此函数将范围转换为单独的数字:

#include <vector>
#include <string>

void push_range_or_number(const std::string &str, std::vector<int> &out) {
    size_t hyphen_index;
    // stoi will store the index of the first non-digit in hyphen_index.
    int first = std::stoi(str, &hyphen_index);
    out.push_back(first);

    // If the hyphen_index is the equal to the length of the string,
    // there is no other number.
    // Otherwise, we parse the second number here:
    if (hyphen_index != str.size()) {
        int second = std::stoi(str.substr(hyphen_index + 1), &hyphen_index);
        for (int i = first + 1; i <= second; ++i) {
            out.push_back(i);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,在连字符处拆分要简单得多,因为我们知道字符串中最多可以有一个连字符。std::string::substr在这种情况下是最简单的方法。请注意,std::stoi如果整数太大而无法放入int.