hello,各位小伙伴,本篇文章跟大家一起学习《C++:string类》,感谢大家对我上一篇的支持,如有什么问题,还请多多指教 !
如果本篇文章对你有帮助,还请各位点点赞!!!
话不多说,开始进入正题
文章目录
- :rocket:什么是string类
- :rocket:string类对象的构造
- 1.:airplane:无参构造
- 2.:airplane:拷贝构造函数
- 3.:airplane:用C-string来构造string类对象
- 4.:airplane:子字符串构造函数
- :rocket:string类对象的访问及遍历操作
- :airplane:1.string类的迭代器`iterator`
- :airplane:2.operator[]
- :airplane:3.begin + end
- :fire:begin
- :fire:end
- :airplane:4.rbegin + rend
- :fire:rbegin
- :fire:rend
- :fire:rbegin + rend结合使用如下:
- :airplane:5.范围for
- :rocket:string类对象的容量操作
- :airplane:1.size
- :airplane:2.capacity
- :airplane:3.empty
- :airplane:4.clear
🚀什么是string类
C语言中,字符串是以’\0’结尾的一些字符的集合,为了操作方便,C标准库中提供了一些str系列的库函数,但是这些库函数与字符串是分离开的,不太符合OOP的思想,而且底层空间需要用户自己管理,稍不留神可能还会越界访问。
OOP是面向对象编程的意思
所以,C++引入了string类。
- 字符串是表示字符序列的类
- 标准的字符串类提供了对此类对象的支持,其接口类似于标准字符容器的接口,但添加了专门用于操作单字节字符字符串的设计特性。
- string类是使用char(即作为它的字符类型,使用它的默认char_traits和分配器类型(关于模板的更多信息,请参阅basic_string)。
- string类是basic_string模板类的一个实例,它使用char来实例化basic_string模板类,并用char_traits和allocator作为basic_string的默认参数(根于更多的模板信息请参考basic_string)。
- 注意,这个类独立于所使用的编码来处理字节:如果用来处理多字节或变长字符(如UTF-8)的序列,这个类的所有成员(如长度或大小)以及它的迭代器,将仍然按照字节(而不是实际编码的字符)来操作。
总结:
- string是表示字符串的字符串类
- 该类的接口与常规容器的接口基本相同,再添加了一些专门用来操作string的常规操作。
- string在底层实际是:basic_string模板类的别名,typedef basic_stringstring;
- 不能操作多字节或者变长字符的序列。
在使用string类时,必须包含#include头文件以及using namespace std;
🚀string类对象的构造
本文章讲的string类对象的构造只讲比较常用的构造方法以及一些细节。
如下为string类对象的构造:
1.✈️无参构造
string();
#include int main() { string s1; return 0; }
此构造为string类的默认构造,构造一个无字符的串(空字符串):
Constructs an empty string, with a length of zero characters.
2.✈️拷贝构造函数
string (const string& str);
#include int main() { string s1("Hello World"); string s2(s1); return 0; }
Constructs a copy of str.
3.✈️用C-string来构造string类对象
string (const char* s);
#include int main() { string s1("hello world"); char C_s[] = "hello world"; string s2(C_s); return 0; }
当然,还可以这么写:
string s3 = "hello world";
这里有个隐式类型转换的过程,"hello world"会生成一个string类的临时对象,赋值给s3
string s3 = "hello world"; const string& s4 = "hello world";
因为临时对象具有常性,所以s4需要用const修饰。
复制s所指向的以null结尾的字符序列(C字符串):
Copies the null-terminated character sequence (C-string) pointed by s.
简单说就是:用一个已有的字符串来初始化。
4.✈️子字符串构造函数
string (const string& str, size_t pos, size_t len = npos);
#include #include using namespace std; int main() { string s1("hello world"); string s2(s1, 0, 5); cout *it = std::toupper(*it); // 将字符转换为大写 } std::cout std::cout string s1("hello world"); for (int i = 0; i