Home > Back-end >  string remove and update
string remove and update

Time:12-27

Trying to remove and replace in string with single loop. For Example :

Input : "the-new-year"

with my code

std::string convert(std::string text) {
    std::string val;
    auto index{ 0 };
    for (auto x : text)
    { 
        if (x != '-')
        {
            val.push_back(x);
            index  ;
        }
        else
        {
            val.push_back(std::toupper(text[index 1]));
            index  ;
        }
    }
    return val;
}

call :convert("the-new-year");

Expected output : "theNewYear"

Getting result : "theNnewYyear" // Error extra character still there

Any suggestions using any STL algo ?

CodePudding user response:

I suggest you do it in two steps:

First capitalize the first letter after a dash. Use a plain iterator or index for loop for this:

std::string val = text;

for (std::size_t i = 0; i < val.length();   i)
{
    if (i > 0 && val[i - 1] == '-')
    {
        val[i] = std::toupper(val[i]);
    }
}

Then using the erase-remove idiom use std::remove and the string erase functions to remove the dashes:

val.erase(std::remove(begin(val), end(val), '-'), end(val));
  • Related