i want to replace a character in the string with a string. can i do it in-place? As the new string has length greater than original string.Question is that can i do with using additional buffer?
for example
void replaceChar(std::string &input, std::string replacementString, char charToReplace)
{
//some code here. No additional buffer
}
void main(){
std::string input = "I am posting a comment on LinkedIn";
std::string replacementString = "pppp";
char charToReplace = 'o';
replaceChar(input, replacementString, charToReplace);
}
I only want the strategy (algorithm). it would be good if algorithm will be designed keeping some language in mind that will not dynamically increase or decrease the string length once it was initilized like c++
std::stringhas areplacemember, but it works in terms of numerical positions, rather than the previous content of the string. As such, you normally have to combine it with thefindmember in a loop, something like this:Personally, I’d rarely get concerned about how often the string gets resized, but if it’s a major concern, you can use
std::countto find the number of occurrences of theoldstring, multiply by the difference in size between the old and new strings, and usestd::string::reserve()to reserve enough space. Note, however, thatreservewas added in C++11 — older implementations won’t have it.Alhough it’s not a concern with the strings you used, this doesn’t work correctly if the replacement string contains an instance of the value being replaced. If you need to deal with that, you’ll need to supply the offset in the string at which to start each search:
Or, you might prefer a
forloop in this case: