在std::string中用一个字符替换所有出现的字符的有效方法是什么
发布于 2010-05-24 19:33:32
std::string不包含这样的函数,但您可以在algorithm头中使用独立的replace函数。
#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'
}发布于 2014-06-20 04:23:11
这个问题集中在character替换上,但是,由于我发现这个页面非常有用(特别是Konrad的评论),我想分享这个更通用的实现,它也允许处理substrings:
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;
}用法:
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执行更改,该字符串通过地址传递,而不是通过值__传递。这将避免对原始字符串进行无用且代价高昂的复制,同时返回结果。你说了算,然后..。
代码:
static inline void ReplaceAll2(std::string &str, const std::string& from, const std::string& to)
{
// Same inner code...
// No return statement
}希望这能对其他人有所帮助。
发布于 2013-02-27 20:10:28
我想我也应该把boost solution也扔进去:
#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, "#", "@");https://stackoverflow.com/questions/2896600
复制相似问题