string容器

目录

1 基本概念

1.1 string和char*的区别:

2 string构造函数

3 string操作

3.1 赋值操作

方式一: = 

方式二: assign

3.2 拼接

​编辑方式一: +=(可追加字符、char*、string类型)

方式二: append

3.3 插入和删除

3.4 查找和替换 

3.4.1 查找

3.4.2 替换

方式一:replace

方式二:通过下标修改

3.5 比较

3.6 遍历字符

3.7 获取子串


1 基本概念

  1. string本质上是一个类
  2. string类内部封装了很多成员方法,例如:查找find、拷贝copy,删除delete,替换replace,插入insert
  3. string管理char*所分配的内存,不用担心复制越界和取值越界等,由类内部进行负责

1.1 string和char*的区别:

  1. char*是指针
  2. string是一个类,类内部封装了char*,管理这个字符串,是一个char*型的容器。

2 string构造函数

函数原型:

  • string();        //创建一个空的字符串,例如string str;   
    • string(const char* s);        //使用字符指针s初始化
  • string(const string& str);     //使用一个string对象初始化另一个string对象
  • string(int n, char c);           //使用n个字符c初始化
#include <iostream>
#include <string>
using namespace std;

void test01(){
	string s1();		//创建一个空的字符串
	
	const char* st1 = "hello world";
	string s2(st1);		//使用字符串st1初始化s2
	
	const string& st2 = "world";
	string s3(st2);		//使用一个string对象初始化另一个string对象
	
	int n = 2;
	char c = 'x';
	string s4(n, c);
	
	cout << "s1 = " << s1 <<endl;
	cout << "s2 = " << s2 <<endl;
	cout << "s3 = " << s3 <<endl;
	cout << "s4 = " << s4 <<endl;
}
int main() {
	test01();
	return 0;
}
1 = 1
s2 = hello world
s3 = world
s4 = xx

3 string操作

3.1 赋值操作

函数原型:

方式一: = 

#include <iostream>
#include <string>
using namespace std;

void test01(){
	string str1;
	str1 = "hello world";
	cout << "str1 = " << str1 << endl;
	
	string str2;
	str2 = str1;
	cout << "str2 = " << str2 << endl;
	
	string str3;
	str3 = 'a';
	cout << "str3 = " << str3 << endl;
}
int main() {
	test01();
	return 0;
}
str1 = hello world
str2 = hello world
str3 = a

方式二: assign

#include <iostream>
#include <string>
using namespace std;

void test01(){
	string str4;
	str4.assign("hello C++");
	cout << "str4 = " << str4 << endl;

	string str5;
	str5.assign(str4);
	cout << "str5 = " << str5 << endl;
	
	string str6;
	str6.assign("hello C++", 5);
	cout << "str6 = " << str6 << endl;
	
	string str7;
	str7.assign(8, 'x');
	cout << "str7 = " << str7 << endl;
}
int main()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值