如何解决在C ++中解析逗号分隔的整数/整数范围 在,处分开解析并添加到std::vector<int>
在C ++中给出一个包含范围和单个数字的字符串:
"2,3,4,7-9"
我想将其解析为以下形式的向量:
2,7,8,9
如果数字之间用-
隔开,那么我想推送该范围内的所有数字。否则,我想输入一个数字。
我尝试使用这段代码:
const char *NumX = "2,4-7";
std::vector<int> inputs;
std::istringstream in( NumX );
std::copy( std::istream_iterator<int>( in ),std::istream_iterator<int>(),std::back_inserter( inputs ) );
问题在于它不适用于范围。它只使用字符串中的数字,而不是范围中的所有数字。
解决方法
您的问题包括两个单独的问题:
- 在
,
处将字符串拆分为多个字符串 - 在解析每个字符串时向向量添加数字或数字范围
如果您首先用逗号分割整个字符串,则不必担心同时用连字符分割。这就是您所说的“分而治之”的方法。
在,
处分开
This question应该告诉您如何用逗号分割字符串。
解析并添加到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);
}
}
}
请注意,在连字符处进行拆分要简单得多,因为我们知道字符串中最多可以有一个连字符。在这种情况下,std::string::substr
是最简单的方法。请注意,如果整数太大而无法放入int
,则std::stoi
会引发异常。
除了@J。 Schultke的出色示例,我建议通过以下方式使用正则表达式:
#include <algorithm>
#include <iostream>
#include <regex>
#include <string>
#include <vector>
void process(std::string str,std::vector<int>& num_vec) {
str.erase(--str.end());
for (int i = str.front() - '0'; i <= str.back() - '0'; i++) {
num_vec.push_back(i);
}
}
int main() {
std::string str("1,2,3,5-6,7,8");
str += "#";
std::regex vec_of_blocks(".*?\,|.*?\#");
auto blocks_begin = std::sregex_iterator(str.begin(),str.end(),vec_of_blocks);
auto blocks_end = std::sregex_iterator();
std::vector<int> vec_of_numbers;
for (std::sregex_iterator regex_it = blocks_begin; regex_it != blocks_end; regex_it++) {
std::smatch match = *regex_it;
std::string block = match.str();
if (std::find(block.begin(),block.end(),'-') != block.end()) {
process(block,vec_of_numbers);
}
else {
vec_of_numbers.push_back(std::atoi(block.c_str()));
}
}
return 0;
}
当然,您仍然需要一点点验证,但是,这将使您入门。
,到目前为止,所有非常好的解决方案。使用现代的C ++和regex,您可以只用很少的几行代码就能做一个多合一的解决方案。
如何?首先,我们定义一个匹配整数或整数范围的正则表达式。看起来像这样
((\d+)-(\d+))|(\d+)
真的很简单。首先是范围。因此,一些数字,然后是连字符和其他一些数字。然后是纯整数:一些数字。所有数字成组放置。 (大括号)。连字符不在匹配组中。
这很容易,不需要进一步解释。
然后我们循环调用std::regex_search
,直到找到所有匹配项。
对于每个匹配项,我们都会检查是否存在子匹配项,即范围。如果我们有一个子匹配项,即一个范围,则将子匹配项之间的值(含)相加到结果std::vector
中。
如果我们只有一个普通整数,则仅添加此值。
所有这些都提供了一个非常简单易懂的程序:
#include <iostream>
#include <string>
#include <vector>
#include <regex>
const std::string test{ "2,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社区版进行编译和测试
,请考虑对您的数字字符串进行预处理并将其拆分。
在下面的代码中,transform()
会将,
-
和+
中的一个delim转换为一个空格,以便std::istream_iterator
成功解析int。>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
int main(void)
{
std::string nums = "2,4-7,9+10";
const std::string delim_to_convert = ",-+"; //,- and +
std::transform(nums.cbegin(),nums.cend(),nums.begin(),[&delim_to_convert](char ch) {return (delim_to_convert.find(ch) != string::npos) ? ' ' : ch; });
std::istringstream ss(nums);
auto inputs = std::vector<int>(std::istream_iterator<int>(ss),{});
exit(EXIT_SUCCESS);
}
请注意,上面的代码只能分割1字节长的delim。如果您需要更复杂,更长的delims,则应参考@ d4rk4ng31答案。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。