This particular assignment has to do with removing substrings from strings; I am trying some of the Stanford SEE courses online to learn some new languages.
What I’ve got so far is below, but if text = "hello hello" and remove ="el", it gets stuck in a loop, but if i change text to text = "hello hllo", it works, making me think I’m doing something obviously stupid.
There is a stipulation in the assignment not to modify the incoming strings, and instead to return a new string.
string CensorString1(string text, string remove){
string returned;
size_t found=0, lastfound=0;
found = (text.substr(lastfound,text.size())).find(remove);
while (string::npos != found ){
returned += text.substr(lastfound,found);
lastfound = found + remove.size();
found = (text.substr(lastfound,text.size())).find(remove);
}
returned += text.substr(lastfound,found);
return returned;
}
Guidance would be appreciated 🙂 Thanks
UPDATE
Took the very kind advice given and modified my code to this :
string CensorString1(string text, string remove){
string returned;
size_t found=0, lastfound=0;
found = text.find(remove);
while (string::npos != found ){
returned += text.substr(lastfound,found);
lastfound = found + remove.length();
found = text.find(remove,lastfound);
}
returned += text.substr(lastfound);
return returned;
}
But still behaves the same
Any more ideas folks?
found = (text.substr(lastfound,text.size())).find(remove);is incorrect. It returns the index of the searched string intext.substr(lastfound,text.size()), but not intext.You should perhaps change this to
found = text.find(text, lastfound);.Besides of being incorrect, taking a substring (this means, allocating a new string) and calculating an index in it is quite inefficient, unless the optimizer is super-smart.
Moreover, the final
returned += text.substr(lastfound,found);is incorrect too: you need to add the last chunk of the text, not the one tillfoundindex (which is most likely empty, aslastfoundcan be smaller thanfound. Better would bereturned += text.substr(lastfound);Edit:
In the second example, you need to replace
returned += text.substr(lastfound,found);
withreturned += text.substr(lastfound,found-lastfound);. The second argument tosubstris length, not position.With this change, the test example runs fine in my test program.
(Addition by J.F. Sebastian:)