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

Find and replace all occurrence of const char* in char*

本文关键字:char const 替换 查找      更新时间:2023-10-16

我正试图创建一个函数来替换char*字符串中出现的所有特定const 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

您的程序已经是未定义的行为,因为您正在丢弃const,像"hello$world$"这样的字符串文字通常放在只读内存中,任何修改它们的尝试都可能导致segfault,您应该使用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);
}
}