C++ string替换单个指定字符为其它字符问题
更新时间:2023年06月06日 09:35:45 作者:Pisces_224
这篇文章主要介绍了C++ string替换单个指定字符为其它字符问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
C++ string替换单个指定字符为其它字符
C++的string提供了replace方法,实现字符串的替换。但是涉及到将string串中的某个字符替换成新的字符的功能,在提供的replace方法中没有实现。
在 #include<algorithm> 中也有一个replace方法,它可以实现我们想要的。
#include <algorithm>
int main()
{
string str = "[1,2,3,4,5]";
cout << str << endl;
replace(str.begin(), str.end(), ',', ' ');//将逗号替换为空格
cout << str << endl;
}[1,2,3,4,5]
[1 2 3 4 5]
C++ std::string 字符串替换
std::string里面std::replace只有单字符替换
std::replace(str.begin(), str.end(), '\"', '@');//单字符替换-----将双引号换成@符
如果有字符串替换的话需要配合find()使用
/// <summary>
/// 字符串批量替换
/// </summary>
/// <param name="str">输入的文本</param>
/// <param name="a">目标文本</param>
/// <param name="b">替换内容</param>
/// <returns>替换好的文本</returns>
std::string spp(std::string str, std::string a, std::string b)
{
int oldPos = 0;
while (str.find(a, oldPos) != -1)//在未被替换的文本中寻找目标文本
{
int start = str.find(a, oldPos);//找到目标文本的起始下标
str.replace(start, a.size(), b);
//从str[start]开始到str[a.size()]替换为b
//str[start]到str[a.size()]也就是a所在得片段
oldPos = start + b.size();//记录未替换文本的起始下标
}
return str;
}int main()
{
std::string str = "{\"QQ1\":123,\"QQ2\":123,\"QQ3\":123}";
str = spp(str, "123", "321");
std::cout << str << std::endl;
str = spp(str, "\"", "\\\"");
std::cout << str << std::endl;
}
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
C++标准模板库STL(Standard Template Library)全解析
C++标准模板库(STL)是一套功能强大的模板类和函数集合,用于提供通用的、可复用的算法和数据结构,STL分为容器、迭代器、算法、函数对象、适配器和分配器等组件,广泛应用于C++编程中,本文介绍C++标准模板库STL(Standard Template Library)详解,感兴趣的朋友一起看看吧2026-01-01
Qt图形图像开发曲线图表模块QChart库基本用法、各个类之间的关系说明
这篇文章主要介绍了Qt图形图像开发曲线图表模块QChart库基本用法、各个类之间的关系说明,需要的朋友可以参考下2020-03-03


最新评论