首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何替换字符串中所有出现的字符?

如何替换字符串中所有出现的字符?
EN

Stack Overflow用户
提问于 2010-05-24 19:30:25
回答 17查看 600.4K关注 0票数 545

std::string中用一个字符替换所有出现的字符的有效方法是什么

EN

回答 17

Stack Overflow用户

回答已采纳

发布于 2010-05-24 19:33:32

std::string不包含这样的函数,但您可以在algorithm头中使用独立的replace函数。

代码语言:javascript
运行
复制
#include <algorithm>
#include <string>

void some_func() {
  std::string s = "example string";
  std::replace( s.begin(), s.end(), 'x', 'y'); // replace all 'x' to 'y'
}
票数 850
EN

Stack Overflow用户

发布于 2014-06-20 04:23:11

这个问题集中在character替换上,但是,由于我发现这个页面非常有用(特别是Konrad的评论),我想分享这个更通用的实现,它也允许处理substrings

代码语言:javascript
运行
复制
std::string ReplaceAll(std::string str, const std::string& from, const std::string& to) {
    size_t start_pos = 0;
    while((start_pos = str.find(from, start_pos)) != std::string::npos) {
        str.replace(start_pos, from.length(), to);
        start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
    }
    return str;
}

用法:

代码语言:javascript
运行
复制
std::cout << ReplaceAll(string("Number Of Beans"), std::string(" "), std::string("_")) << std::endl;
std::cout << ReplaceAll(string("ghghjghugtghty"), std::string("gh"), std::string("X")) << std::endl;
std::cout << ReplaceAll(string("ghghjghugtghty"), std::string("gh"), std::string("h")) << std::endl;

输出:

Number_Of_Beans

XXjXugtXty

hhjhugthty

编辑:

在您关心性能的情况下,可以以更合适的方式实现上述功能,方法是不返回任何值,并直接对作为参数给定的字符串str执行更改,该字符串通过地址传递,而不是通过值__传递。这将避免对原始字符串进行无用且代价高昂的复制,同时返回结果。你说了算,然后..。

代码:

代码语言:javascript
运行
复制
static inline void ReplaceAll2(std::string &str, const std::string& from, const std::string& to)
{
    // Same inner code...
    // No return statement
}

希望这能对其他人有所帮助。

票数 147
EN

Stack Overflow用户

发布于 2013-02-27 20:10:28

我想我也应该把boost solution也扔进去:

代码语言:javascript
运行
复制
#include <boost/algorithm/string/replace.hpp>

// in place
std::string in_place = "blah#blah";
boost::replace_all(in_place, "#", "@");

// copy
const std::string input = "blah#blah";
std::string output = boost::replace_all_copy(input, "#", "@");
票数 140
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2896600

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档