Reputation: 2569
I have a string with ranges like eg. "0-0,4-7,9-9", and I need to find out all ranges with same start and end and modify to them to "0,4-7,9".
I am not at ease with string manipulation and c++ so need some help.
Input String: "0-0,2-7,8-8,88-108" Output String: "0,2-7,8,88-108"
Maximum digit value could be 4000 only.
In PHP I would need to do something like this in loop:
$pos = strpos($vlan_ranges, ",");
$number_range = strtok($number_ranges, ",");
$number = split("-", $range);
$number_start = $number[0];
$number_end = $number[1];
But dont know how this could be done in c++. Not familiar with c++ syntax. Any help is greatly appreciated.
Added: I have to this using standard String class alone. I can not use string manipulation engines.
Upvotes: 0
Views: 315
Reputation: 2569
while ( (orig_str.find(",") != std::string::npos) && (orig_str.find("-") != std::string::npos) )
{
sub = orig_str.substr(0, orig_str.find_first_of(","));
orig_str = orig_str.substr(orig_str.find_first_of(",")+1);
cout << "sub = " << sub << endl;
cout << "orig_str = " << orig_str << endl;
if (sub.substr(0,sub.find_first_of("-")) == sub.substr(sub.find_first_of("-")+1) )
{
sub.erase(0, sub.find_first_of("-")+1);
cout << "sub2 = " << sub << endl;
final = final + sub + ",";
cout << "final = " << final << endl;
}
else
{
final = final + sub + ",";
}
}
cout << "final2 = " << final << endl;
Upvotes: 0
Reputation: 5002
I think something like this could work:
std::string str = "1-1,2-3,4-4,...";
size_t number_digits;
for (size_t i = 0; i < str.size(); ++i)
{
if(str.find("-", i)) != std::string::npos))
{
number_digits = str.find_first_of(",", i) - i - 1;
if (str.substr(i - number_digits, i - 1) == str.substr(i + 1, i + number_digits))
str.erase(i-number_digits, number_digits + 1);
}
}
Edit: actually I posted an infinite loop. Fixed now.
Upvotes: 2