C++ string replace操作

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

1、单个字符替换

1.1、单个字符替换

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

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

#include <string>
#include <string.h>
#include <stdio.h>

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

结果如下:

在这里插入图片描述

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

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

#include <string>
#include <string.h>
#include <stdio.h>

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

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

输出结果:
在这里插入图片描述

下面代码是一个字符串向后面替换3个字符串测试demo,只用把结束字符串数改成3即可,下过如下:
在这里插入图片描述

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

接着上面的代码进行测试,使用3个字符串向后面替换3个字符串测试demo,只用把结束字符串数改成3即可,下过如下:
在这里插入图片描述
经过测试单字符设置多个字符串替换的时候只是复制了多次该单字符

2、字符串替换

2.1、字符串替换

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


#include <string>
#include <string.h>
#include <stdio.h>

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

	printf("Outpath1:%s\n", outPath.c_str());


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

结果如下图:
在这里插入图片描述

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

在这里插入图片描述

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

在这里插入图片描述
注意,结果是错的!切勿此操作

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

指定好覆盖长度即可,如下图:
在这里插入图片描述
以上,总结完毕!辉·2022.8.5

  • 1
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值