24.C++之STL(二)

学习目标:

在这里插入图片描述

学习内容:

1.string 容器

string是C++风格的字符串,char是C语言风格的。二者的区别是:

  • char *是一个指针;
  • string是一个类,内部封装了char*,管理该字符串,是一个char*型的容器;

特点:

  • string类的内部封装了很多的成员方法,如查找(find)、插入(insert);
  • string管理char*所分配的内存,不用担心复制越界和取值越界等,由类内部进行负责。

1.1 string 构造函数

#include<iostream>
#include<string>
using namespace std;
void test()
{
	string s="hello C++";//赋值
	cout << s << endl;

	string s1(10, '+');//10个+号
	cout << s1 << endl;
}
int main()
{
	test();
	system("pause");
	return 0;
}

在这里插入图片描述

1.2 string 拼接

#include<iostream>
#include<string>
using namespace std;
void test()
{
	string s="中国";
	s += ",万岁!!!";
	cout << s << endl;

}
int main()
{
	test();
	system("pause");
	return 0;
}

在这里插入图片描述

1.3 string 查找和替换

#include<iostream>
#include<string>
using namespace std;
void test()
{
	string s = "I love China!";
	//查找
	cout << s.find("C") << endl; //返回位置的索引
	//替换
	s.replace(0,1, "We");
	cout << s << endl;
}
int main()
{
	test();
	system("pause");
	return 0;
}

在这里插入图片描述

1.4 string 比较

#include<iostream>
#include<string>
using namespace std;
void test()
{
	string s1 = "I love China!";
	string s2 = s1;
	if (s1.compare(s2) == 0) //两者比较返回值为-1、0、1;
	{
		cout << "两者相等!!!!!!";
	}
}
int main()
{
	test();
	system("pause");
	return 0;
}

在这里插入图片描述

1.5 string 存取

语法为:
中括号[]或者at()

#include<iostream>
#include<string>
using namespace std;
void test()
{
	string s1 = "I love China!";
	cout << s1[0] << endl;
	cout << "------------------" << endl;
	cout << s1.at(0) << endl;
}
int main()
{
	test();
	system("pause");
	return 0;
}

在这里插入图片描述

1.6 string 插入和删除

#include<iostream>
#include<string>
using namespace std;
void test()
{
	string s1 = "ABCDEFG";
	//插入
	s1.insert(0, "T");
	cout << s1 << endl;
	cout << "------------------" << endl;
	//删除
	s1.erase(1, 3);//从1号位置开始删除3个元素
	cout << s1 << endl;
}
int main()
{
	test();
	system("pause");
	return 0;
}

在这里插入图片描述

1.7 子串获取

语法:
str.substr(pos,int n)从位置pos开始,获取n个元素。

#include<iostream>
#include<string>
using namespace std;
void test()
{
	string s1 = "ABCDEFG";
	s1 = s1.substr(0, 3);
	cout << s1 << endl;
}
int main()
{
	test();
	system("pause");
	return 0;
}

在这里插入图片描述

1.7.1 子串获取应用
#include<iostream>
#include<string>
using namespace std;
void test()
{
	string s1 = "欧阳娜娜@qq.com";
	int pos = s1.find("@");
	s1 = s1.substr(0, pos);
	cout << s1 << endl;
}
int main()
{
	test();
	system("pause");
	return 0;
}

在这里插入图片描述


学习时间:

提示:这里可以添加计划学习的时间

例如:

  • 周一至周五晚上 7 点—晚上9点
  • 周六上午 9 点-上午 11 点
  • 周日下午 3 点-下午 6 点

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值