什么是有效的方法来取代一个字符的所有出现与另一个字符在std::字符串?
当前回答
老派:-)
std::string str = "H:/recursos/audio/youtube/libre/falta/";
for (int i = 0; i < str.size(); i++) {
if (str[i] == '/') {
str[i] = '\\';
}
}
std::cout << str;
结果:
点:youtube \ resources \音响\ \‘\ \缺失
其他回答
Std::string不包含这样的函数,但你可以使用独立的替换函数从算法头。
#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'
}
正如Kirill建议的那样,要么使用replace方法,要么沿着字符串迭代,单独替换每个字符。
或者,您可以使用find方法或find_first_of,这取决于您需要做什么。这些解决方案都不能一次性完成工作,但是通过几行额外的代码,您应该让它们为您工作。: -)
这不是标准库中缺少的唯一方法,它本来是低级别的。 这个用例和许多其他用例由通用库涵盖,例如:
波科 绳降 提高 QtCore
QtCore & QString有我的偏好:它支持UTF8,使用更少的模板,这意味着可以理解的错误和更快的编译。它使用了“q”前缀,使命名空间变得不必要,并简化了头文件。 Boost经常生成可怕的错误消息和缓慢的编译时间。 POCO似乎是一种合理的妥协。
我想我会使用std::replace_if()
一个简单的字符替换程序(OP要求的)可以使用标准库函数编写。
就地版本:
#include <string>
#include <algorithm>
void replace_char(std::string& in,
std::string::value_type srch,
std::string::value_type repl)
{
std::replace_if(std::begin(in), std::end(in),
[&srch](std::string::value_type v) { return v==srch; },
repl);
return;
}
如果输入是const字符串,则返回一个副本的重载:
std::string replace_char(std::string const& in,
std::string::value_type srch,
std::string::value_type repl)
{
std::string result{ in };
replace_char(result, srch, repl);
return result;
}
如果你想替换一个以上的字符,并且只处理std::string,那么这个代码片段可以工作,用sReplace替换sHaystack中的sNeedle,而且sNeedle和sReplace不需要相同的大小。这个例程使用while循环替换所有发生的事件,而不是只替换从左到右找到的第一个事件。
while(sHaystack.find(sNeedle) != std::string::npos) {
sHaystack.replace(sHaystack.find(sNeedle),sNeedle.size(),sReplace);
}
推荐文章
- cbegin/cend背后的原因是什么?
- 如何在Eclipse CDT中启用c++ 11/ c++ 0x支持?
- 将string (or char*)转换为wstring (or wchar_t*)
- 如何停止c++控制台应用程序从退出立即?
- 有没有替换Windows (Visual C)的unistd.h ?
- 目标文件中无法解析的外部符号
- Lambda捕获作为const引用?
- 如何从c风格数组初始化std::vector ?
- 是std::vector复制对象push_back?
- 计算趋势主题或标签的最佳方法是什么?
- 为什么在c++ 11中使用非成员begin和end函数?
- 如何通过参数和重定向stdin从一个文件到程序运行在gdb?
- 为什么两个不同的概念都叫“堆”?
- 如何找到JavaScript数组中包含的最大数字?
- 为什么这个结合赋值和相等检查的if语句返回true?