【C++】STL 容器 - string 字符串操作 ⑥ ( string 字符替换 - replace 函数替换字符串 | string 字符交换值 - swap 函数交换字符串 )






一、string 字符替换 - replace 函数替换字符串



1、string 类 replace 函数原型说明


replace 函数简介 : 该函数 的作用是 从位置 pos 开始 , 替换长度为 n 的 子字符串 为 s , 如果 s 的长度与 n 不相等 , 那么原字符串的其余部分也会相应地移动 ;

  • 首先 , 删除从 pos 开始的 n 个字符 ;
  • 然后 , 在 pos 处插入 字符串 s ;

replace 函数原型 :

string& replace(int pos, int n, const char* s);
string& replace(int pos, int n, const string& s);
  • 参数说明 :
    • pos : 要替换的子字符串的起始位置 , 位置从 0 开始计数 ;
    • n : 要替换的子字符串的长度 ;
    • s : 要替换为的新字符串 ;
  • 返回值说明 : 返回一个指向修改后的字符串的引用 ; 返回的仍然是 字符串 本身 ,

2、代码示例 - 字符串替换


在下面的代码中 , 删除从 0 位置开始的 3 个字符 , 然后在 0 位置处插入 Jack 字符串 , 最终返回的 string& 类型的引用 就是 原字符串的引用 ;

	// 删除从 0 位置开始的 3 个字符
	// 然后在 0 位置处插入 Jack 字符串
	// 返回的索引仍然是字符串本身
	string s2 = s1.replace(0, 3, "Jack");

代码示例 :

#include "iostream"
using namespace std;
#include "string"

int main() {
    
    

	string s1 = "Tom And Jerry, Hello World, Tom !";

	// 删除从 0 位置开始的 3 个字符
	// 然后在 0 位置处插入 Jack 字符串
	// 返回的索引仍然是字符串本身
	string s2 = s1.replace(0, 3, "Jack");

	// 打印 s1 和 返回的字符串
	cout << "s1 = " << s1 << endl;
	cout << "s2 = " << s2 << endl;


	// 控制台暂停 , 按任意键继续向后执行
	system("pause");

	return 0;
};

执行结果 :

s1 = Jack And Jerry, Hello World, Tom !
s2 = Jack And Jerry, Hello World, Tom !
请按任意键继续. . .

在这里插入图片描述





二、string 字符交换值 - swap 函数交换字符串



1、string 类 swap 函数原型说明


string 类 swap 函数 原型 : 该函数会交换 当前字符串 和 参数 s2 的内容值 , 在交换过程中 , 两个字符串的内容会相互交换 , 但它们在内存中的位置保持不变 ;

void swap(string& s2);

参数说明 : s2 参数 是 与 当前字符串进行交换的另一个字符串 ;


2、代码示例 - swap 函数交换值


代码示例 :

#include "iostream"
using namespace std;
#include "string"

int main() {
    
    

	string s1 = "Tom And Jerry";
	string s2 = "Hello World";

	// 交换 s1 与 s2 的值
	s1.swap(s2);

	// 打印 s1 和 s2 值
	cout << "s1 = " << s1 << endl;
	cout << "s2 = " << s2 << endl;


	// 控制台暂停 , 按任意键继续向后执行
	system("pause");

	return 0;
};

执行结果 :

s1 = Hello World
s2 = Tom And Jerry
请按任意键继续. . .

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/han1202012/article/details/135043449
今日推荐