Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
689 views
in Technique[技术] by (71.8m points)

c++ - Replace char in string with some string inplace


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++

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

std::string has a replace member, 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 the find member in a loop, something like this:

std::string old("o");

int pos;

while ((pos = x.find(old)) != std::string::npos)
    x.replace(pos, old.length(), "pppp");

Personally, I'd rarely get concerned about how often the string gets resized, but if it's a major concern, you can use std::count to find the number of occurrences of the old string, multiply by the difference in size between the old and new strings, and use std::string::reserve() to reserve enough space. Note, however, that reserve was added in C++11 -- older implementations won't have it.

Edit: though it's not a concern with the strings you used, as @ipc pointed out, 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:

int pos = 0;

while ((pos = x.find(old, pos)) != std::string::npos) {
    x.replace(pos, old.length(), rep);
    pos += rep.length();
}

Or, you might prefer a for loop in this case:

    std::string old("o");
    std::string rep("pop");

for (int pos=0; 
    (pos = x.find(old, pos)) != std::string::npos; 
    pos+=rep.length())
{
    x.replace(pos, old.length(), rep);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...