In order to obtain {4,а}345{2,о} from аааа345рр , that is, to implement Run Length Coding (RLE) :
template<class InputIt, class OutputIt> OutputIt rle_encode(InputIt first, InputIt last, OutputIt d_first) { if (first == last) // empty return d_first; auto prev = *first++; // previous char uintmax_t count = 1; for ( ; first != last; ++first, ++count) { if (prev != *first) { // ended run of the same consecutive elements d_first = write_rle_run(d_first, prev, count); // write the run prev = *first; // start new run count = 0; } } return write_rle_run(d_first, prev, count); }
This is a translation from Python's rle_encode () function .
write_rle_run() writes the found series of characters in a row to the result:
template<class OutputIt, class C> OutputIt write_rle_run(OutputIt d_first, C character, uintmax_t count) { if (count > 1) { *d_first++ = '{'; for (char digit : std::to_string(count)) *d_first++ = digit; *d_first++ = ','; *d_first++ = character; *d_first++ = '}'; } else { assert(count == 1); *d_first++ = character; } return d_first; }
This also works for an array:
const char a[] = "aaaa345pp"; char output[5*(sizeof a)/2]; rle_encode(std::begin(a), std::end(a), output);
and for string:
std::string text = "aaaa345pp"; std::string s; rle_encode(std::begin(text), std::end(text), std::back_inserter(s));
and for input / output streams:
std::istream_iterator<char> chars{std::cin}, eof; rle_encode(chars, eof, std::ostream_iterator<char>(std::cout));
Full code example .
In the write_rle_run() you can transfer the desired number of repetitions from the user and adapt the if (count > 1) condition.
To perform the conversion in the opposite direction, you can use rle_decode() .
while (str[i+1]!='\0') { if (str[i] == str[i + 1]) for (int x=0;(x<"размер строки" && str[x]!='\0');x++)then I make a replacement where the size of the string changes accordingly, the size needs to be updated, the problem is here. - LokenGarvel '