1. The issues in your code:
There are several issues, some bugs and some bad practices (see side notes below).
To begin with, std::string::substr
's second parameter is count
- i.e. the number of characters. So in your case it should simply be 3
. You also don't check that i < s.length()-3
before using substr
.
Then the whole logic of your loop is flawed. Using a debuggers will help you to get more insight. See: What is a debugger and how can it help me diagnose problems?.
2. A better approach:
If you want to remove a substring from a string, you can do the following:
- Use
std::string::find
to find the substring.
- Then use
std::string::erase
to remove it.
Code example:
#include <iostream>
#include <string>
int main()
{
std::string str = "WUBhello";
std::string toRemove = "WUB";
// Find the substring:
auto pos = str.find(toRemove);
if (pos != std::string::npos)
{
// Remove it:
str.erase(pos, toRemove.length());
}
std::cout << str << std::endl;
return 0;
}
Output:
hello
If you want to remove multiple occurances of the substring, you can apply similar logic in a loop:
// Find the 1st occurance substring:
auto pos = str.find(toRemove);
while (pos != std::string::npos)
{
// Remove it:
str.erase(pos, toRemove.length());
// Find the next one:
pos = str.find(toRemove);
}
Some side notes:
- Why should I not #include <bits/stdc++.h>?
- Why is "using namespace std;" considered bad practice?