Search code examples
c++stringif-statementstdstring

Replacing a substring with a space character


I am given a string and I have to remove a substring from it. Namely WUB, and replace it with a space character.

There are 2 WUB's between ÁRE' and 'THE'. SO the first condition in if statement is for not printing two blank spaces but on executing the code two blank spaces are being printed.

Input:  WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB
Output: WE ARE THE CHAMPIONS MY FRIEND 

Here is my code so far:

#include <iostream>

using namespace std;

int main()
{
    const string check = "WUB";
    string s, p;
    int ct = 0;
    cin >> s;

    for (int i = 0; i < s.size(); i++)
    {
        if (s[i] == 'W' && s[i+1] == 'U' && s[i+2] == 'B')
        {
            i += 2;
            if (p[ct] == '32' || p.empty())
            {
                continue;
            }
            else
            {
                p += ' ';
                ct++;
            }
        }
        else
        {
            p += s[i];
            ct++;
        }
    }

    cout << p;
    return 0;
}

Why is the first if statement never executed?


Solution

  • There are actually three bugs here, so it's probably worth to conclude them in one answer:

    1. The first condition:

      if (s[i] == 'W' && s[i+1] == 'U' && s[i+2] == 'B')
      

      is out of bounds for the last two characters. One fix would be to check the length first:

      if(i < s.length() - 2 && s[i] == 'W' && s[i+1] == 'U' && s[i+2] == 'B')
      
    2. There's a multicharacter-literal in

      if (p[ct] == '32' || p.empty())  
      

      Use ' ' or 32 or std::isspace instead. IMO the last one is the best.

    3. In the same condition

      p[ct] == '32' 
      

      is always out of bounds: ct is equal to p.length(). (Credits to Some programmer dude, who mentioned this in the comments!) The variable ct is also redundant, since std::string knows it's length. I suggest to use std::string::back() to access the last character and reorder the condition as so:

      if (p.empty() || std::isspace(p.back()))