到目前为止所有非常好的解决方案。使用现代 C++ 和正则表达式,您只需几行代码即可完成一体化解决方案。
怎么样?首先,我们定义一个匹配整数或整数范围的正则表达式。它看起来像这样
((\d+)-(\d+))|(\d+)
真的很简单。先说范围。所以,一些数字,后跟一个连字符和更多数字。然后是普通整数:一些数字。所有数字都分组。 (大括号)。连字符不在匹配组中。
这一切都很简单,无需进一步解释。
然后我们循环调用std::regex_search,直到找到所有匹配项。
对于每个匹配,我们检查是否有子匹配,表示一个范围。如果我们有子匹配,一个范围,那么我们将子匹配之间的值(包括)添加到结果std::vector。
如果我们只有一个普通整数,那么我们只添加这个值。
所有这些都给出了一个非常简单易懂的程序:
#include <iostream>
#include <string>
#include <vector>
#include <regex>
const std::string test{ "2,3,4,7-9" };
const std::regex re{ R"(((\d+)-(\d+))|(\d+))" };
std::smatch sm{};
int main() {
// Here we will store the resulting data
std::vector<int> data{};
// Search all occureences of integers OR ranges
for (std::string s{ test }; std::regex_search(s, sm, re); s = sm.suffix()) {
// We found something. Was it a range?
if (sm[1].str().length())
// Yes, range, add all values within to the vector
for (int i{ std::stoi(sm[2]) }; i <= std::stoi(sm[3]); ++i) data.push_back(i);
else
// No, no range, just a plain integer value. Add it to the vector
data.push_back(std::stoi(sm[0]));
}
// Show result
for (const int i : data) std::cout << i << '\n';
return 0;
}
如果您还有其他问题,我很乐意回答。
语言:C++ 17
使用 MS Visual Studio 19 社区版编译和测试