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:%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;
}

结果如下:

C++ string replace操作_第1张图片

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

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

#include 
#include 
#include 

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;
}

输出结果:
C++ string replace操作_第2张图片

下面代码是一个字符串向后面替换3个字符串测试demo,只用把结束字符串数改成3即可,下过如下:
C++ string replace操作_第3张图片

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

接着上面的代码进行测试,使用3个字符串向后面替换3个字符串测试demo,只用把结束字符串数改成3即可,下过如下:
C++ string replace操作_第4张图片
经过测试单字符设置多个字符串替换的时候只是复制了多次该单字符

2、字符串替换

2.1、字符串替换

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


#include 
#include 
#include 

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;
}

结果如下图:
C++ string replace操作_第5张图片

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

C++ string replace操作_第6张图片

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

C++ string replace操作_第7张图片
注意,结果是错的!切勿此操作

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

指定好覆盖长度即可,如下图:
C++ string replace操作_第8张图片
以上,总结完毕!辉·2022.8.5

你可能感兴趣的:(笔记心得,C++,c++)