C++初阶-string的使用

一、为什么学习string类

1.1 C语言中的字符串

  C语言中,字符串是以’\0’结尾的一些字符的集合,为了操作方便,C标准库中提供了一些str系列的库函数,但是这些库函数与字符串是分离开的,不太符合OOP的思想,而且底层空间需要用户自己管理,稍不留神可能还会越界访问。
  在OJ中,有关字符串的题目基本以string类的形式出现,而且在常规工作中,为了简单、方便、快捷,基本
都使用string类,很少有人去使用C库中的字符串操作函数。
cin中连续输入默认是以空格或者换行进行分割的
getline则遇到空格不结束,默认遇到换行才结束 getline(cin,str)
getline(cin,str,“!”) 则遇到!结束,遇到空格和换行都不结束
stoi函数用于将字符串转换为整数
to_string函数用于将非字符串类型的变量转换为字符串类型

二、标准库中的string类

2.1 string类

  1. 字符串是表示字符序列的类
  2. 标准的字符串类提供了对此类对象的支持,其接口类似于标准字符容器的接口,但添加了专门用于操作单字节字符字符串的设计特性。
  3. string类是使用char(即作为它的字符类型,使用它的默认char_traits和分配器类型。
  4. string类是basic_string模板类的一个实例,它使用char来实例化basic_string模板类,并用char_traits
    和allocator作为basic_string的默认参数。
  5. 注意,这个类独立于所使用的编码来处理字节:如果用来处理多字节或变长字符(如UTF-8)的序列,这个
    类的所有成员(如长度或大小)以及它的迭代器,将仍然按照字节(而不是实际编码的字符)来操作。

总结:

  1. string是表示字符串的字符串类。
  2. 该类的接口与常规容器的接口基本相同,再添加了一些专门用来操作string的常规操作。
  3. string在底层实际是:basic_string模板类的别名,typedef basic_string<char, char_traits, allocator>
    string;
  4. 不能操作多字节或者变长字符的序列。
    在使用string类时,必须包含#include头文件以及using namespace std;

2.2 string类的常见接口说明

2.2.1 string类对象的常见构造

函数名称功能说明
string() (重点)构造空的string类对象,即空字符串
string(const char* s) (重点)用C-string来构造string类对象
string(size_t n, char c)string类对象中包含n个字符c
string(const string&s) (重点)拷贝构造函数
int main()
{
	string s1;   //定义无参
	string s2("hello world");   //带参可以用const char*的常量字符串初始化

	string ret1=s1+s1;    
	string ret2=s1+"我来了";
	
	string s3 = "hello world";  //类型转换(const char*转换成 string)  构造+拷贝构造 -优化成->构造
	string s4(s3, 6, 3);        //从第6个位置开始取3个字符
	cout << s4 << endl;
	//cin >> s1; //流插入
	//cout << s1  //流提取

	string s5(s3, 6, 13);   //如果字符长度小于要取的字符就直接取到结尾,最后一个参数不给的话也默认取到结尾
	cout << s5 << endl;

	string s7("hello world", 5); //用字符串的前5个字符去构造
	cout << s7 << endl;

	string s8(10, '*');       //在string中填10个*
	cout << s8 << endl;


	for (size_t i = 0; i < s2.size(); ++i)    //[]可以读可以写  size是字符的长度
	{
		s2[i]++;
	}
	cout << s2 << endl;   //重载了流插入和流提取

	for (size_t i = 0; i < s2.size(); ++i)
	{
		cout << s2[i] << " ";
	}

	string::iterator it =s1.begin()    //可以读也可以进行写  []和迭代器都是可读可写
	while(it!=s1.end())
	{
		cout<<*it<<" ";
		++it; 
	}
	cout<<endl;

	string::reverse_iterator it =s1.rbegin()  //反向迭代器,通常倒着遍历就使用反向迭代器
	while(rit != s1.rend())
	{	
		cout << *rit << " ";
		++rit;
	}
	cout<<endl;

	for (auto ch : s1)    //范围for 数组和容器都可使用 (不支持修改,如果需要就要用&)  //原理:编译器替换成迭代器
	{
		cout << ch << " "
	}

	string filename;
	cin>>filename;
	FILE* fout= fopen(filename.c_str(),"r");

	return 0;
}

2.2.2 string类对象的容量操作

函数名称功能说明
size (重点)返回字符串有效字符长度 (不包括\0)
length返回字符串有效字符长度(不包括\0)
capacity返回空间总大小
empty (重点)检测字符串释放为空串,是返回true,否则返回false
clear (重点)清空有效字符 (不会释放空间)
reserve (重点)为字符串预留空间**
resize (重点)将有效字符的个数改成n个,多出的空间用字符c填充
insert插入字符
erase删除字符
replace替换字符
find查找字符
int main()
{
	string s1("hello world");
	cout << s1.size() << endl;  //求长度  后出现
	cout << s1.length() << endl;//求长度  先出现
	cout << s1.max_size() << endl; //求最大值  实际中没有太大的参考价值
	cout << s1.capacity() << endl; //求字符串容量的大小 (不包含\0)

	//扩容
	string s1("hello world");
	s1.reserve(100);
	cout << s1.size() << endl;
	cout << s1.capacity() << endl;

	//扩容+初始化
	string s2("hello world");
	s2.resize(100,'x');
	cout << s2 << endl;
	cout << s2.size() << endl;
	cout << s2.capacity() << endl;

	//比size小,删除数据,保留前5个  不会改变capacity
	s2.resize(5);
	cout << s2.size() << endl;
	cout << s2.capacity() << endl;
	
	return 0;
}
int main()
{
	string s1("world");
	s1.insert(0, "hello");    //在0这个位置插入一个字符串
	cout << s1 << endl;

	s1.insert(5, 1, ' ');   //在5这个位置插入一个空格
	cout << s1 << endl;
	s1.insert(5, " ");
	cout << s1 << endl;
	s1.insert(s1.begin() + 5, ' ');
	cout << s1 << endl;

	string s2("hello world");
	s2.erase(5, 1);   //从第5个位置开始删除,删一个字符
	s2.erase(s2.begin() + 5);
	cout << s2 << endl;

	s2.erase(5, 30);  //如果要删除的字符个数大于字符个数就有多少删多少
	s2.erase(5);
	cout << s2 << endl;
}
int main()
{
	string s1("hello world");
	s1.replace(5, 1, "%%d");  //从第5个位置开始的一个字符替换为%%d
	cout << s1 << endl;
	
	size_t pos = s1.find(' ');
	while (pos != string::npos)
	{
		s1.replace(pos, 1, "%20");   //将pos位置的1个字符替换为%20
		pos = s1.find(' ', pos + 3);
	}
	cout << s1 << endl;
}

注意:

  1. size()与length()方法底层实现原理完全相同,引入size()的原因是为了与其他容器的接口保持一致,一般情况下基本都是用size()。
  2. clear()只是将string中有效字符清空,不改变底层空间大小。
  3. resize(size_t n) 与 resize(size_t n, char c)都是将字符串中有效字符个数改变到n个,不同的是当字符个数增多时:resize(n)用0来填充多出的元素空间,resize(size_t n, char c)用字符c来填充多出的元素空间。注意:resize在改变元素个数时,如果是将元素个数增多,可能会改变底层容量的大小,如果是将元素个数减少,底层空间总大小不变。
  4. reserve(size_t res_arg=0):为string预留空间,不改变有效元素个数,当reserve的参数小于string的底层空间总大小时,reserver不会改变容量大小。

2.2.3 string类对象的访问及遍历操作

函数名称功能说明
operator[] (重点)返回pos位置的字符,const string类对象调用
begin+endbegin获取一个字符的迭代器+end获取最后一个字符下一个位置的迭代器
rbegin+rendbegin获取一个字符的迭代器+end获取最后一个字符下一个位置的迭代器
范围forC++支持更简介的范围for的新遍历方式
int main()
{
	string s1("hello world");
	string::iterator it = s1.begin();
	while (it != s1.end())
	{
		cout << *it << " ";
		++it;
	}
	cout << endl;

	string::reverse_iterator rit = s1.rbegin();
	while (rit != s1.rend())
	{
		cout << *rit << " ";
		++rit;
	}
	cout << endl;

	string::const_iterator it = s1.begin();
	while (it != s1.end())
	{
		//*it+=1;
		cout << *it << " ";
		++it;
	}
	cout << endl;

	string::const_reverse_iterator it = s1.begin();
	while (it != s1.end())
	{
		//*it+=1;
		cout << *it << " ";
		++it;
	}
	cout << endl;

	for (auto ch : s1)
	{
		cout << ch << " ";
	}
	cout << endl;

	return 0;
}

2.2.4 string类对象的修改操作

函数名称功能说明
push_back在字符串后尾插字符c
append在字符串后追加一个字符串
operator+=(重点)在字符串后追加字符串str
c_str(重点)返回c格式字符串
find+npos (重点)从字符串pos位置开始往后找字符c,返回该字符在字符串中的位置
rfind从字符串pos位置开始往前找字符c,返回该字符在字符串中的位置
substr在str中从pos位置开始,截取n个字符,然后将其返回
find_first_of从前往后找任意包含字符串中的字符,返回那个字符的下标,否则返回npos
find_last_of从后往前找任意包含字符串中的字符,返回那个字符的下标,否则返回npos
int main()
{
	string s1("hello");
	s1.push_back(' ');//在后面插入字符
	s1.push_back('!');
	cout << s1 << endl;

	s1.append("world");//在后面插入一个字符串
	cout << s1 << endl;

	s1 += ' ';  //+=运算符重载  后面可以跟字符或者字符串
	s1 += '!';
	s1 += "world";
	cout << s1 << endl;
	return 0;
}
int main()
{
	string s1("hello world");
	cout << s1 << endl;
	cout << s1.c_str() << endl;
}
int main()
{
	string file("string.cpp.tar.zip");
	size_t pos = file.rfind(".");
	if (pos != string::npos)
	{
		string suffix = file.substr(pos,file.size() - pos);
		string suffix = file.substr(pos);
		cout << suffix << endl;
	}

	return 0;
}
int main()
{
	std::string str("Please, replace the vowels in this sentence by asterisks.");
	std::size_t found = str.find_first_of("abcdv");
	while (found != std::string::npos)
	{
		str[found] = '*';
		found = str.find_first_of("abcdv", found + 1);
	}
	std::cout << str << '\n';

	string s1("hello world");
	string s2("hello world");
	s1 == s2;
	s1 == "hello world";
	"hello world" == s1;

	return 0;
}

注意:

  1. 在string尾部追加字符时,s.push_back© / s.append(1, c) / s += 'c’三种的实现方式差不多,一般情况下string类的+=操作用的比较多,+=操作不仅可以连接单个字符,还可以连接字符串。
  2. 对string操作时,如果能够大概预估到放多少字符,可以先通过reserve把空间预留好。

2.2.5 string类非成员函数

函数名称功能说明
operator+尽量少用,因为传值返回,导致深拷贝效率低
operator>> (重点)输入运算符重载
operator<<(重点)输出运算符重载
getline(重点)获取一行字符串
relational operators (重点)大小比较

2.2.6 vs和g++下string结构的说明

vs下string的结构
  string总共占28个字节,内部结构稍微复杂一点,先是有一个联合体,联合体用来定义string中字符串的存储空间:
1.当字符串长度小于16时,使用内部固定的字符数组来存放
2.当字符串长度大于等于16时,从堆上开辟空间
这种设计也是有一定道理的,大多数情况下字符串的长度都小于16,那string对象创建好之后,内部已经有了16个字符数组的固定空间,不需要通过堆创建,效率高。
其次:还有一个size_t字段保存字符串长度,一个size_t字段保存从堆上开辟空间总的容量
最后:还有一个指针做一些其他事情。
故总共占16+4+4+4=28个字节。
g++下string的结构
  g++下,string是通过写时拷贝实现的,string对象总共占4个字节,内部只包含了一个指针,该指针将来指向一块堆空间,内部包含了如下字段:
1.空间总大小
2.字符串有效长度
3.引用计数
4.指向堆空间的指针,用来存储字符串。

  • 20
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值