查找并替换char*中所有出现的const char*
Find and replace all occurrence of const char* in char*
我正试图创建一个函数来替换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);
}
}
相关文章:
- 在字符串函数中抛出'char const*'实例后调用的终止
- 双重标准?为什么只有 char* const&a = "bla" 的警告?
- 包括"lvtocon.h",未定义对'operator<<(std::ostream&, char const*)的引用
- 为什么 const char* const & = 可以编译"hello"?
- 将字符串文本常量定义为 char const* 和 wchar const*
- 如何将std::wstring转换为char const[]
- "char const * name() const _WEBSOCKETPP_NOEXCEPT_TOKEN_ {"剂量是什么意思
- 使用提升对字符串进行标记化时,将令牌转换为 char* const* 时失败
- 如何从 std::initializer_list<char const* 构建 std::vector<std::string>>
- 将 std::vector<std::string> 转换为 const char* const*
- 引发"char const*"错误的实例后调用的终止
- 将const char * const参数成员分配给新值
- 从'const char**'到'char* const*'的转换无效
- 从 sub_match<常量字符 *>' 转换为'const char *const &'
- char*const和constchar*之间有什么区别?(重复-需要更多澄清)
- 使用工厂方法时编译器错误:无法转换"const std::p air<char* const
- HEVC 解码器端口 Android 警告:从 'signed char*' 到 'char const* 的转换无效*
- 如何从'char const*'中删除常量
- 'char const *str'作为模板参数
- 为什么不;t strlen(.)应为const char*const str,而不是const char*