什么是有效的方法来取代一个字符的所有出现与另一个字符在std::字符串?
当前回答
Abseil StrReplaceAll怎么样?在头文件中:
// This file defines `absl::StrReplaceAll()`, a general-purpose string
// replacement function designed for large, arbitrary text substitutions,
// especially on strings which you are receiving from some other system for
// further processing (e.g. processing regular expressions, escaping HTML
// entities, etc.). `StrReplaceAll` is designed to be efficient even when only
// one substitution is being performed, or when substitution is rare.
//
// If the string being modified is known at compile-time, and the substitutions
// vary, `absl::Substitute()` may be a better choice.
//
// Example:
//
// std::string html_escaped = absl::StrReplaceAll(user_input, {
// {"&", "&"},
// {"<", "<"},
// {">", ">"},
// {"\"", """},
// {"'", "'"}});
其他回答
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'
}
#include <iostream>
#include <string>
using namespace std;
// Replace function..
string replace(string word, string target, string replacement){
int len, loop=0;
string nword="", let;
len=word.length();
len--;
while(loop<=len){
let=word.substr(loop, 1);
if(let==target){
nword=nword+replacement;
}else{
nword=nword+let;
}
loop++;
}
return nword;
}
//Main..
int main() {
string word;
cout<<"Enter Word: ";
cin>>word;
cout<<replace(word, "x", "y")<<endl;
return 0;
}
老派:-)
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 \音响\ \‘\ \缺失
这不是标准库中缺少的唯一方法,它本来是低级别的。 这个用例和许多其他用例由通用库涵盖,例如:
波科 绳降 提高 QtCore
QtCore & QString有我的偏好:它支持UTF8,使用更少的模板,这意味着可以理解的错误和更快的编译。它使用了“q”前缀,使命名空间变得不必要,并简化了头文件。 Boost经常生成可怕的错误消息和缓慢的编译时间。 POCO似乎是一种合理的妥协。
如果你想替换一个以上的字符,并且只处理std::string,那么这个代码片段可以工作,用sReplace替换sHaystack中的sNeedle,而且sNeedle和sReplace不需要相同的大小。这个例程使用while循环替换所有发生的事件,而不是只替换从左到右找到的第一个事件。
while(sHaystack.find(sNeedle) != std::string::npos) {
sHaystack.replace(sHaystack.find(sNeedle),sNeedle.size(),sReplace);
}
推荐文章
- 为什么这个结合赋值和相等检查的if语句返回true?
- cplusplus.com给出的错误、误解或坏建议是什么?
- 找出质数最快的算法是什么?
- c++枚举类可以有方法吗?
- 格式化IO函数(*printf / *scanf)中的转换说明符%i和%d之间的区别是什么?
- 圆线段碰撞检测算法?
- 将析构函数设为私有有什么用?
- 求有向图中的所有循环
- main()中的Return语句vs exit()
- 为什么c#不提供c++风格的'friend'关键字?
- JavaScript -从当前日期开始获取一周的第一天
- 在函数的签名中添加关键字
- 我如何在Visual Studio中预处理后看到C/ c++源文件?
- 为什么在标准容器中使用std::auto_ptr<>是错误的?
- 用比较double和0