C ++でコンマ区切りのint / int範囲を解析します
範囲と種類の単一の数値を含むC ++の文字列を指定します。
"2,3,4,7-9"
私はそれを次の形式のベクトルに解析したいと思います:
2,3,4,7,8,9
数字がaで区切られて-
いる場合は、範囲内のすべての数字をプッシュします。それ以外の場合は、単一の番号をプッシュしたいと思います。
私はこのコードを使ってみました:
const char *NumX = "2,3,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 ) );
問題は、それが範囲に対して機能しなかったことでした。範囲内のすべての数値ではなく、文字列内の数値のみを取得しました。
回答
@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;
}
もちろん、まだ少し検証が必要ですが、これで始められます。
あなたの問題は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);
}
}
}
文字列には最大で1つのハイフンが含まれることがわかっているため、ハイフンでの分割ははるかに簡単であることに注意してください。std::string::substrこの場合、これを行う最も簡単な方法です。std::stoi整数が大きすぎてint
。に収まらない場合は、例外がスローされる可能性があることに注意してください。
これまでのすべての非常に素晴らしいソリューション。最新の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 CommunityEditionでコンパイルおよびテスト済み
数値文字列を前処理して分割することを検討してください。次のコードでは、transform()
delimsの1を変換し、う,
-
と+
するように空間に、std::istream_iterator
成功した解析int型。
#include <cstdlib>
#include <algorithm>
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
int main(void)
{
std::string nums = "2,3,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バイトの長さのデリムしか分割できないことに注意してください。より複雑で長いデリムが必要な場合は、@ d4rk4ng31の回答を参照してください。