1、为什么学习string类?
1、1C语言中的字符串
C语言中,字符串是以'\0'结尾的一些字符的集合,为了操作方便,C标准库中提供了一些str系列的库函数, 但是这些库函数与字符串是分离开的,不太符合OOP的思想(即面向对象思想),而且底层空间需要用户自己管理,稍不留神可能还会越界访问。
1、2 面试题
力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
在OJ中,有关字符串的题目基本以string类的形式出现,而且在常规工作中,为了简单、方便、快捷,基本都使用string类,很少有人去使用C库中的字符串操作函数。
2、标准库中的string类
2、1string类
string类的文档介绍:
http://www.cplusplus.com/reference/string/string/?kw=string
1. 字符串是表示字符序列的类
2. 标准的字符串类提供了对此类对象的支持,其接口类似于标准字符容器的接口,但添加了专门用于操作 单字节字符字符串的设计特性。
3. string类是使用char(即作为它的字符类型,使用它的默认char_traits和分配器类型(关于模板的更多信 息,请参阅basic_string)。
4. string类是basic_string模板类的一个实例,它使用char来实例化basic_string模板类,并用char_traits 和allocator作为basic_string的默认参数(根于更多的模板信息请参考basic_string)。
5. 注意,这个类独立于所使用的编码来处理字节:如果用来处理多字节或变长字符(如UTF-8)的序列,这个 类的所有成员(如长度或大小)以及它的迭代器,将仍然按照字节(而不是实际编码的字符)来操作。
总结:
1. string是表示字符串的字符串类。
2. 该类的接口与常规容器的接口基本相同,再添加了一些专门用来操作string的常规操作。
3. string在底层实际是:basic_string模板类的别名,typedef basic_string string;
4. 不能操作多字节或者变长字符的序列。
在使用string类时,必须包含#include头文件以及using namespace std; 。
2、2string类的常用接口说明,只讲常用的
2、2、1string类对象的常见构造
(constructor)函数名称 | 功能说明 |
string() (重点) | 构造空的string类对象,即空字符串 |
string(const char* s) (重点) | 用C-string来构造string类对象 |
string(size_t n, char c) | string类对象中包含n个字符c |
string(const string& s,size_t pos,isze_t len = npos) | 拷贝s的pos位置开始向后len个字符 |
string(const char* s,size_t n) | 拷贝s指向的字符串的前n个字符 |
string(const string&s) (重点) | 拷贝构造函数 |
int main()
{
string s1;
string s2("hello world!");
string s3(s2);
string s4(4, 'c');
string s5(s2,6,5);
string s6("hello world", 5);
cout << s1 << endl;//
cout << s2 << endl;//hello world
cout << s3 << endl;//hello world
cout << s4 << endl;//cccc
cout << s5 << endl;//world
cout << s6 << endl;//hello
return 0;
}
2、2、2string类对象的容量操作
函数名称 | 功能说明 |
size(重点) | Returns the length of the string, in terms of bytes. |
length | Returns the length of the string, in terms of bytes. |
capacity | Returns the size of the storage space currently allocated for the string, expressed in terms of bytes.(返回当前为字符串分配的存储空间的大小,以字节表示。) |
empty (重点) | Returns whether the string is empty(true or false) |
clear (重点) | Erases the contents of the string, which becomes an empty string (with a length of 0 characters).(清空有效字符) |
reserve(size_t n) (重点) | Requests that the string capacity be adapted to a planned change in size to a length of up to n characters.(请求字符串容量适应最大长度为n个字符的计划大小更改) |
resize (重点) |