0

I have a string that's in the form similar to:

"1111P1P"

I'm trying to replace all sub strings of ones by the total:

i.e. "4P1P"

The string will always contain 1's and no other numbers before replacement.

My initial idea was to split the string using regex and store it in a vector and i could manipulate it. But this removes the delimiters as well.

std::string newDes = "1111P1P";
std::vector<std::string> desSplit; 
std::regex re1("[^0-9]");
std::sregex_token_iterator first1{newDes.begin(), newDes.end(), re1, -1}, 
desSplit = {first1, last1};

Any help would really be appreciated.

nablue
  • 67
  • 1
  • 6

2 Answers2

2

A single loop will allow you to complete this with O(n) runtime:

std::string str = "1111P1P";

std::string final;
int running_total = 0;
for(auto ch : str) {
    if(ch == '1') { 
        running_total++;
        continue;
    }

    if(running_total > 0) { final += std::to_string(running_total); }
    final += ch;
    running_total = 0;
}

// In case we ended on a '1'
if(running_total > 0) { final += std::to_string(running_total); }

See it in action: https://ideone.com/x1BkHy

scohe001
  • 15,110
  • 2
  • 31
  • 51
0

Try something like this:

std::string newDes = "1111P1P";
size_t start = 0, end, count;
while ((start = newDes.find('1', start)) != std::string::npos)
{
    if ((end = newDes.find_first_not_of('1', start+1)) == std::string::npos)
        end = newDes.size();
    count = end - start;
    std::string replacement = std::to_string(count);
    newDes.replace(start, count, replacement);
    start += replacement.size();
}

Online Demo

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770