-2

I got a code. It should give me an output that will erase the middle character between 'z' and 'p'. for example: zipZap("zipXzap"): expected [zpXzp] but found [z pXz p]

std::string zipZap(const std::string& str){
    string a = str;  
    string b = "";
    size_t len = str.length();
    for (size_t i = 0; i < len; i++){
        if (str[i] == 'z')
            if (str[i+2] == 'p')
                a[i+1] = ' ';
    }
    return a;
}

When i replaced a[i+1] = ''; it gave me an error.

user3326237
  • 71
  • 1
  • 1
  • 4

4 Answers4

0

You are not removing the chars, you are replacing them with ' '.

There are many ways to do this. One simple way is to build a new string, only adding chars when the proper conditions are met:

std::string zipZap(const std::string& str)
{
    string a;  
    size_t len = str.length();
    for (size_t i = 0; i < len; i++) {
        // Always add first and last chars. As well as ones not between 'z' and 'p'
        if (i == 0 || i == len-1 || (str[i-1] != 'z' && str[i+1] != 'p')) {
            a += str[i];
        }
    }
    return a;
}
001
  • 13,291
  • 5
  • 35
  • 66
0

Use string.erase() :

std::string zipZap(const std::string& str){
    std::string a = str;
    std::string b = "";
    size_t len = str.length();
    for (size_t i = 0; i < len; i++){
        if (a[i] == 'z')
            if (a[i+2] == 'p')
                a.erase(i+1,1);
    }
    return a;
}
Captain GouLash
  • 1,257
  • 3
  • 20
  • 33
0

You're completely right that you cant replace an element of the string with ''. A string is an array of chars, and '' is not a char at all. It is nothing. If we look at the cplusplus page for a string

http://www.cplusplus.com/reference/string/string/

We see that we can use erase(iterator p) to "Erase characters from string (public member function)"

So if we change:

for (size_t i = 0; i < len; i++){
    if (str[i] == 'z')
        if (str[i+2] == 'p')
            a.erase(a.begin() + i + 1);

We're closer now, but we can see that len is no longer the same as str.length(). the length of a is now actually 1 char shorter than len. To remedy this however we can simply add:

for (size_t i = 0; i < len; i++){
    if (str[i] == 'z')
        if (str[i+2] == 'p')
            a.erase(a.begin() + i + 1);
            len -= 1;

Hope that helps

flakes
  • 21,558
  • 8
  • 41
  • 88
0

If you #include <regex>, you can do a regular expression replacement.

std::string zipZap(const std::string& str){
    regex exp("z.p");
    string a = str;
    a = regex_replace(a, exp "zp");
    return a;
}
McLovin
  • 3,554
  • 1
  • 14
  • 15