栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ string replace操作

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ string replace操作

C++ string replace操作本来网上有很多,但是按其操作有坑,编译提示语法错误。所以特此记录:
参考链接(有坑):

目录
    • 1、单个字符替换
      • 1.1、单个字符替换
      • 1.2、延申1:一个字符串向后面替换多个字符串测试代码:
      • 1.3、延申2:多个字符串向后面替换多个字符串测试代码:
    • 2、字符串替换
      • 2.1、字符串替换
      • 2.2、使用字符串(长度小于原字符串)来替换单字符,测试代码:
      • 2.3、使用字符串(长度大于原字符串)来替换单字符,测试代码:
      • 2.4、使用字符串来替换字符串,测试代码:

1、单个字符替换 1.1、单个字符替换

这里有一个需求,把路径中所有正斜杠改成反斜杠(/ --> )

replace(起始位置,替换字符长度,待替换字符长度,待替换字符)
Demo如下:

#include 
#include 
#include 

using namespace std;
int main()
{
	string outPath = "F:/11JIAMIEXE/2Bin/";;//测试用1个字符串替换一个字符串的效果
	printf("Outpath1:%sn", outPath.c_str());
	while (outPath.find('/') != outPath.npos)
	{
		outPath = outPath.replace(outPath.find('/'),1,1, '\');//测试用1个字符串替换一个字符串的效果。起始位置、终止位置、替换字符串个数、替换的字符串
		printf("Outpath2:%sn", outPath.c_str());
	}
	printf("Result:%sn", outPath.c_str());
	return 0;
}

结果如下:

1.2、延申1:一个字符串向后面替换多个字符串测试代码:

下面代码是一个字符串向后面替换2个字符串测试demo:

#include 
#include 
#include 

using namespace std;
int main()
{
	string outPath = "F:/11JIAMIEXE/2Bin/";
	printf("Outpath1:%sn", outPath.c_str());

	//auto startSize = outPath.find('/');
	while (outPath.find('/') != outPath.npos)
	{
		outPath = outPath.replace(outPath.find('/'),2,1, '\');//测试用1个字符串替换两个字符串。起始位置、终止位置、替换字符串个数、替换的字符串
		printf("Outpath2:%sn", outPath.c_str());
	}
	printf("Result:%sn", outPath.c_str());
	return 0;
}

输出结果:

下面代码是一个字符串向后面替换3个字符串测试demo,只用把结束字符串数改成3即可,下过如下:

1.3、延申2:多个字符串向后面替换多个字符串测试代码:

接着上面的代码进行测试,使用3个字符串向后面替换3个字符串测试demo,只用把结束字符串数改成3即可,下过如下:

经过测试单字符设置多个字符串替换的时候只是复制了多次该单字符

2、字符串替换 2.1、字符串替换

字符串替换的方法略微变通一下即可:
replace(起始位置,终止位置,字符串,字符串长度)
使用字符串来替换单字符,测试代码:

#include 
#include 
#include 

using namespace std;
int main()
{
	string outPath = "F:/11JIAMIEXE/2Bin/";//测试用1个字符串替换两个字符串

	printf("Outpath1:%sn", outPath.c_str());


	while (outPath.find('/') != outPath.npos)
	{
		outPath = outPath.replace(outPath.find('/'),1, "ABC",3);//字符串替换
		printf("Outpath2:%sn", outPath.c_str());
	}
	printf("Result:%sn", outPath.c_str());
	return 0;
}

结果如下图:

2.2、使用字符串(长度小于原字符串)来替换单字符,测试代码:

2.3、使用字符串(长度大于原字符串)来替换单字符,测试代码:


注意,结果是错的!切勿此操作

2.4、使用字符串来替换字符串,测试代码:

指定好覆盖长度即可,如下图:

以上,总结完毕!辉·2022.8.5

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1033292.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号