Replace char in string with some string inplace

前端 未结 4 1712
刺人心
刺人心 2021-01-14 16:16


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

4条回答
  •  情歌与酒
    2021-01-14 16:45

    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);
    }
    

提交回复
热议问题