查找并替换char *中所有出现的const char *

时间:2018-08-02 08:35:05

标签: c++ string replace

我正在尝试创建一个函数来替换const char*字符串中所有特定char*的出现。

这是我的代码:

#include <iostream>

void replace(char **bufp, const char *searchStr, const char *replaceStr)
{
    //what should I do here?
}

int main()
{
    char *txt = const_cast<char *>("hello$world$");
    replace(&txt, "$", "**");
    std::cout << "Result: " << txt << '\n';
}

我得到的结果:

Result: hello$world$
Program ended with exit code: 0

我想要的结果

Result: hello**world**
Program ended with exit code: 0

1 个答案:

答案 0 :(得分:3)

您的程序已经是未定义的行为,因为您要抛弃const,通常将"hello$world$"之类的字符串文字放置在只读内存中,并且任何对其进行修改的尝试都可能会导致段错误。改用std::string

使用std::string,您的替换功能可能如下所示:

void replace(std::string& str, const std::string& find, const std::string& replace)
{
    std::size_t position{};
    while((position = str.find(find)) != std::string::npos){
          str.erase(position,find.size());
          str.insert(position,replace);
    }
}
相关问题