There's a string with the word "WUB" in it, and I need to eliminate this word from the string.
So I used the substring method inside the if block so that while traversing the loop, if block can catch the WUB and instead print 1
#include <bits/stdc .h>
using namespace std;
int main()
{
string s="WUBhello";
for(int i=0;i<s.length();i ){
if(s.substr(i,i 2)=="WUB"){
cout<<"1 ";
i =2;
}
else{
cout<<s[i];
}
}
return 0;
}
I'm expecting it will print only "hello" , but it's printing "WUBhello"
CodePudding user response:
You can use std::stringstream
too.
Note: Do check the function signature of any standard library function before using it.
std::substr
's second argument is length of substring.
#include <string>
#include <sstream>
#include <iostream>
std::string remove_substring(const std::string& s, const std::string& key)
{
std::stringstream ss;
for (int i = 0; i < s.length(); )
{
if (s.substr(i, key.length()) == key)
{
i = key.length();
}
else
{
ss << s[i];
i ;
}
}
return ss.str();
}
int main()
{
const std::string s = "WUBhello";
const std::string key = "WUB";
std::cout << remove_substring(s, key);
}
CodePudding user response:
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:
CodePudding user response:
The second argument of std::string::substr
is exclusive, so it should be i 3
. Also, even when the logic is correct, it will print "1 hello".