C 语言中,字符串是以 '\0' 结尾的一些字符的集合,为了操作方便,C 标准库中提供了一些 str 系列的库函数,但是这些库函数与字符串是分离开的,不太符合 OOP 的思想,而且底层空间需要用户自己管理,稍不留神可能还会越界访问。C++ STL 中的 string 是对字符串进行管理的类。实际上就是一个管理字符数组的顺序表。
在常规工作中,为了简单、方便、快捷,基本都会选择二使用 string 类,很少有人去使用 C 语言库中的字符串操作函数。
https://cplusplus.com/reference/string/string/?kw=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_string<char, char_traits, allocator> string;- 不能操作多字节或者变长字符的序列。
在使用string 类时,必须包含 #include 头文件以及 using namespace std;
ASCII (American Standard Code for Information Interchange):美国信息交换标准代码是基于拉丁字母的一套电脑编码系统。ASCII 到目前为止共定义了 128 个字符。
在计算机中,所有的数据在存储和运算时都要使用二进制数表示。例如,像 a、b、c、d 这样的 52 个字母(包括大写)以及 0、1 等数字还有一些常用的符号(例如 *、#、@ 等)在计算机中存储时也要使用二进制数来表示,而具体用哪些二进制数字表示哪个符号,当然每个人都可以约定自己的一套(这就叫编码)。
ASCII 码使用指定的 7 位或 8 位二进制数组合来表示 128 或 256 种可能的字符。标准 ASCII 码也叫基础 ASCII 码,使用 7 位二进制数(剩下的 1 位二进制为 0)来表示所有的大写和小写字母,数字 0 到 9、标点符号,以及在美式英语中使用的特殊控制字符。
常见 ASCII 码的大小规则:数字 < 大写字母 < 小写字母。
UTF-8(8 位元,Universal Character Set/Unicode Transformation Format)是针对 Unicode 的一种可变长度字符编码。它可以用来表示 Unicode 标准中的任何字符,而且其编码中的第一个字节仍与 ASCII 相容,使得原来处理 ASCII 字符的软件无须或只进行少部分修改后,便可继续使用。
Unicode 的编码方式有三种:UTF-8、UTF-16、UTF-32( UTF 后的数字代表编码的最小单位,如UTF-8 表示最小单位 1 字节)。由于 UTF-8 与字节序无关(无需 BOM ),同时兼容 ASCII 编码,使得 UTF-8 编码成为现今互联网信息编码标准而被广泛使用。
https://cplusplus.com/reference/string/string/?kw=string
- string(); // 默认构造
- string (const char* s); // 用c-string来构造string类对象
- string (size_t n, char c); // 用n个字符c来构造string对象
- string (const string& s); // 拷贝构造(用已有的string类对象去构造string类对象)
- ===========================================================================================
- string (const char* s, size_t n); // 用c-string前n个字符来构造string类对象
- template <class InputIterator> // 用迭代器[first,last)范围内的字符序列构造string类对象
- string (InputIterator first, InputIterator last);
-
-
- #include
- #include
- using namespace std;
-
- int main()
- {
- string s0 ("Initial string");
- string s1; // s1: ""
- string s2 (s0); // s2: Initial string
- string s4 ("A character sequence"); // s4: A character sequence
- string s5 ("Another character sequence", 12); // s5: Another char
- string s6 (10, 'x'); // s6: xxxxxxxxxx
- string s7 (s0.begin(), s0.begin() + 7); // s7: Initial
- return 0;
- }

string 容量相关方法使用代码演示:
- #include
- #include
- using namespace std;
-
- // 测试string容量相关的接口:size/length/capacity/clear/resize
- void Tests1()
- {
- string s("hello world!");
- cout << s.size() << endl; //12
- cout << s.length() << endl; //12
- cout << s.capacity() << endl; //15
- cout << s << endl; //hello world!
-
- // 将s中的字符串清空,注意清空时只是将size清0,不改变capacity的大小
- s.clear();
- cout << s.size() << endl; //0
- cout << s.capacity() << endl; //15
-
-
- // 将s中有效字符个数增加到10个,多出的位置用'a'进行填充
- // “aaaaaaaaaa”
- s.resize(10, 'a');
- cout << s.size() << endl; //10
- cout << s.capacity() << endl; //15
-
-
- // 将s中有效字符个数增加到20个,多出位置用缺省值'\0'进行填充
- // 如果resize参数大于原有 capacity 大小,会进行增容
- // "aaaaaaaaaa\0\0\0\0\0\0\0\0\0\0"
- // 注意此时s中有效字符个数已经增加到20个
- s.resize(15);
- cout << s.size() << endl; //20
- cout << s.capacity() << endl; //31
- cout << s << endl; //aaaaaaaaaa
-
-
- // 将s中有效字符个数缩小到5个
- s.resize(5);
- cout << s.size() << endl; //5
- cout << s.capacity() << endl; //31
- cout << s << endl; //aaaaa
- }
- void Tests2()
- {
- // 测试string容量相关的接口:size/capacity/reserve
- string s("Hello abcdefghi");
-
- // 如果reserve参数大于原有capacity大小,会进行增容
- s.reserve(20);
- cout << s.size() << endl; //15
- cout << s.capacity() << endl; //31
-
- // reserve参数小于string的底层空间大小时,不会将空间缩小
- // 在VS2019下,如果size大于参数10,不会缩小。
- // 如果字符串长度小于参数10,会缩小。当然,这个也和编译器平台有关系
- s.reserve(10);
- cout << s.size() << endl; //15
- cout << s.capacity() << endl; //31
- }
利用 reserve 提高插入数据的效率,避免增容带来的开销。
如果 n 大于当前字符串容量,则该函数使容器将其容量增加到 n 个字符 / 更大。
在所有其他情况下,缩小字符串容量被视为非绑定请求:容器可以自由实现优化,但要保留容量大于 n 的字符串。
此函数对字符串长度没有影响,并且不能更改其内容。
- void TestPushBack()
- {
- string s;
- size_t sz = s.capacity();
- cout << "making s grow:\n";
- for (int i = 0; i < 100; ++i)
- {
- s.push_back('c');
- if (sz != s.capacity())
- {
- sz = s.capacity();
- cout << "capacity changed: " << sz << '\n';
- }
- }
- }
而在 Linux g++ 下是 2 倍增容。
构建 vector 时,如果提前已经知道 string 中大概要放多少个元素,可以提前将 string 中空间设置好。
- void TestPushBackReserve()
- {
- string s;
- s.reserve(100);
- size_t sz = s.capacity();
-
- cout << "making s grow:\n";
- for (int i = 0; i < 100; ++i)
- {
- s.push_back('c');
- if (sz != s.capacity())
- {
- sz = s.capacity();
- cout << "capacity changed: " << sz << '\n';
- }
- }
- }
- reserve 的作用:如果知道需要多大的空间,可以利用 reserve 提前一次性把空间开好,避免增容带来的开销。
- resize 的作用:既要开好空间,还要对这些空间初始化,就可以使用 resize。
- void Tests3()
- {
- string s1("hello World");
- const string s2("Hello World");
- cout << s1 << " " << s2 << endl;
- cout << s1[0] << " " << s2[0] << endl;
-
- s1[0] = 'H';
- cout << s1 << endl;
- // s2[0] = 'h'; //编译失败,因为const类型对象不能修改
- }
【总结】
- size() 与 length() 方法底层实现原理完全相同,引入 size() 的原因是为了与其他容器的接口保持一致,一般情况下基本都是用 size()。
- clear() 只是将 string 中有效字符清空,不改变底层空间(capacity)大小。
- resize(size_t n) 与 resize(size_t n, char c) 都是将字符串中有效字符个数改变到 n 个,不同的是当字符个数增多时:resize(n) 用 0 来填充多出的元素空间,resize(size_t n, char c) 用字符 c 来填充多出的元素空间。注意:resize 在改变元素个数时,如果是将元素个数增多,可能会改变底层容量的大小,如果是将元素个数减少,底层空间总大小不变。
- reserve(size_t res_arg=0):为 string 预留空间,不改变有效元素个数,当 reserve 的参数小于 string 的底层空间总大小时,reserver 不会改变容量大小。
cplusplus.com/reference/string/string/operator[]/
string 中元素访问及遍历代码演示:
string 的遍历:
- for+operator[]
- 迭代器
- 范围 for
注意:string 遍历时使用最多的还是 for+ 下标 / 范围 for(C++11 后才支持)。
begin() + end() 大多数使用在需要使用 STL 提供的算法操作 string 时,比如:采用 reverse 逆置 string。需要注意的以上三种方式除了遍历 string 对象,还可以遍历是修改 string 中的字符。另外这三种方式对于 string 而言,第一种使用最多。
- // const对象必须要用const迭代器
- void test(const std::string& s)
- {
- string::const_iterator it = s.begin();
- while (it != s.end())
- {
- cout << *it;
- it++;
- }
- }
-
- void Tests4()
- {
- string s("hello World");
-
- // 1、for+operator[]
- for (size_t i = 0; i < s.size(); ++i)
- {
- cout << s[i] << " ";
- }
- cout << endl;
-
- // 2、迭代器(正向)
- string::iterator it = s.begin();
- // 注意:这里不建议写成it
- while (it != s.end())
- {
- cout << *it << " ";
- ++it;
- }
- cout << endl;
-
- // 2、迭代器(反向)
- // string::reverse_iterator rit = s.rbegin();
- // C++11之后,直接使用auto定义迭代器,让编译器推到迭代器的类型
- auto rit = s.rbegin(); // 创建一个反向迭代器rit,指向字符串s的最后一个字符
- while (rit != s.rend()) // 当反向迭代器不等于s的逆向结束迭代器时
- {
- cout << *rit << " ";
- ++rit; // 将迭代器向前移动一位
- }
- cout << endl;
-
- // 3、范围for(支持迭代器的容器就支持范围for)
- for (auto ch : s)
- {
- cout << ch << " ";
- }
- cout << endl;
- }

注意:operator[] 函数会检查越界(pos 必须 < size)
尽量不要用 insert() 和 erase(),因为要挪动字符,时间效率低。
- push_back 将一个字符附加到字符串的末尾(尾插)
- swap 交换两个字符串的内容(注意:还存在一个具有相同名称的非成员函数 swap)
- void Tests5()
- {
- string s;
- s.push_back(' '); // 在s后插入空格
- s.append("hello"); // 在s后追加一个字符串"hello"
- s += 'w'; // 在s后追加一个字符'w'
- s += "orld"; // 在s后追加一个字符串"orld"
- cout << s << endl; // helloworld
- cout << s.c_str() << endl; // 以C语言的方式打印字符串 helloworld
-
- // 获取file的后缀
- string file("string.cpp");
- size_t pos = file.rfind('.');
- string suffix(file.substr(pos, file.size() - pos));
- cout << suffix << endl; //.cpp
-
- // 取出url中的域名
- string url("http://www.cplusplus.com/reference/string/string/find/");
- cout << url << endl; //http://www.cplusplus.com/reference/string/string/find/
- size_t start = url.find("://");
- if (start == string::npos)
- {
- cout << "invalid url" << endl;
- return;
- }
- start += 3;
- size_t finish = url.find('/', start);
- string address = url.substr(start, finish - start);
- cout << address << endl; //www.cplusplus.com
-
- // 删除url的协议前缀
- pos = url.find("://");
- url.erase(0, pos + 3);
- cout << url << endl; //www.cplusplus.com/reference/string/string/find/
- }
注意 :
- 在 string 尾部追加字符时,s.push_back(c) / s.append(1, c) / s += 'c' 三种的实现方式都差不多,一般情况下 string 类的 += 操作用的比较多,+= 操作不仅可以连接单个字符,还可以连接字符串。operator+=,是在当前字符串末尾追加字符串(追加 string / char* / char 类型的都可以)。
- 对 string 操作时,如果能够大概预估到放多少字符,可以先通过 reserve 把空间预留好。
npos 在 string 里面是一个静态成员变量。(static const size_t npos = -1;)
- relational operators:关系运算符,进行大小比较
- std::swap:交换两个字符串的值
- 注意:getline:直到遇到换行符 ‘\n’ 才会结束。
string s; getline(cin, s);
C 语言库文件
【字符处理函数】
- int isalpha(int c):如果 c 是一个字母,则该函数返回非零值,否则返回 0。
- int isdigit(int c):如果 c 是一个数字,则该函数返回非零值,否则返回 0。
【字符转换函数】
- int tolower(int c):如果 c 有相对应的小写字母,则该函数返回 c 的小写字母,否则 c 保持不变。返回值是一个可被隐式转换为 char 类型的 int 值。
- int toupper(int c):如果 c 有相对应的大写字母,则该函数返回 c 的大写字母,否则 c 保持不变。返回值是一个可被隐式转换为 char 类型的 int 值。
头文件
中:
- 函数 std::to_string(C++11):将数值转换为字符串,返回 string 类对象。cplusplus.com/reference/string/to_string/
- 函数 std::stoi(C++11):将字符串转换为整数,返回 int 整数。cplusplus.com/reference/string/stoi/
头文件
中:
- 函数 std::reverse:反转范围 [first,last) 中元素的顺序。
- 函数 std::sort:将 [first,last) 范围内的元素按升序排序。(传一段迭代器区间 [first, last),默认排升序,若要排降序,需要传仿函数)
注意 :下述结构是在 32 位平台下进行验证,32 位平台下指针占 4 个字节。
string 总共占 28 个字节,内部结构稍微复杂一点,先是有一个联合体,联合体用来定义 string 中字 符串的存储空间:
- 当字符串长度小于 16 时,使用内部固定的字符数组来存放。
- 当字符串长度大于等于 16 时,从堆上开辟空间。
- union _Bxty
- { // storage for small buffer or pointer to larger one
- value_type _Buf[_BUF_SIZE];
- pointer _Ptr;
- char _Alias[_BUF_SIZE]; // to permit aliasing
- } _Bx;
这个联合体的目的是为了在存储较小的数据时使用数组,而在存储较大的数据时使用指针。通过使用联合体,可以在相同的内存空间中灵活地存储不同类型的数据。
注意:联合体的成员变量共享同一块内存空间,因此在使用时需要确保对应的成员变量是有效的。
G++ 下,string 是通过写时拷贝实现的,string 对象总共占 4 个字节,内部只包含了一个指针,该指针将来指向一块堆空间,内部包含了如下字段:
- 空间总大小
- 字符串有效长度
- 引用计数
- struct _Rep_base
- {
- size_type _M_length;
- size_type _M_capacity;
- _Atomic_word _M_refcount;
- };
- 指向堆空间的指针,用来存储字符串。
模拟实现 string 类,最主要是实现 string 类的构造、拷贝构造、赋值运算符重载以及析构函数。
浅拷贝 :也称位拷贝,编译器只是将 对象中的数据 按字节序拷贝过来。 如果对象中管理资源,最后就会导致多个对象共享同一份资源,当一个对象销毁时就会将该资源释放掉,而此时另一些对象不知道该资源已经被释放,以为 还有效,所以当继续对资源进项操作时,就会发生发生了访问违规。
- // 为了和标准库区分,此处使用String
- class String
- {
- public:
- // 构造函数
- String(const char* pStr = "")
- {
- // 构造String类对象时,如果传递nullptr指针,可以认为程序非法
- if (nullptr == pStr)
- {
- assert(false);
- return;
- }
- _pStr = new char[strlen(pStr) + 1];
- strcpy(_pStr, pStr);
- }
-
- // 析构函数
- ~String()
- {
- if (_pStr)
- {
- delete[] _pStr;
- _pStr = nullptr;
- }
- }
- private:
- char* _str;
- };
-
- void test()
- {
- string s1("hello"); // 用一个常量字符串去构造string类对象s1
- string s2(s1); // s2调用编译器默认生成的拷贝构造函数
- }
说明:上述 String 类没有显式定义其拷贝构造函数与赋值运算符重载,此时编译器会合成默认的,当用 s1 构造 s2 时,编译器会调用默认的拷贝构造。最终导致的问题是,s1、s2 共用同一块内存空间,在释放时同一块空间被释放多次而引起程序崩溃,这种拷贝方式,称为浅拷贝。

这里必须是深拷贝,编译器默认生成的拷贝构造函数是浅拷贝,会导致两个 string 对象中的字符指针 _str 指向的是同一个字符数组。(因为浅拷贝只拷贝了 _str 数组指针的 4 个字节的内容)。

所以在上述类中必须要显式定义拷贝构造函数,否则编译器默认生成的拷贝构造函数无法正常完成拷贝。那么我们可以 采用深拷贝解决浅拷贝问题 ,即:每个对象都有一份独立的资源,不要和其他对象共享。
浅拷贝引发的问题:
- 同一块空间会被析构多次。
- 一个对象修改会影响另外一个对象。
如果一个类中涉及到资源的管理,其拷贝构造函数、赋值运算符重载以及析构函数必须要显式给出。一般情况都是按照深拷贝方式提供。深拷贝:给每个对象独立分配资源,保证多个对象之间不会因为共享资源问题而造成多次释放资源,导致程序崩溃。
- class String
- {
- public:
- String(const char* str = "")
- {
- // 构造String类对象时,如果传递nullptr指针,可以认为程序非法
- if (nullptr == str)
- {
- assert(false);
- return;
- }
- _str = new char[strlen(str) + 1];
- strcpy(_str, str);
- }
-
- // 拷贝构造
- String(const String& s) // 保护形参不被改变,加引用防止无穷递归
- : _str(new char[strlen(s._str) + 1]) // 给新对象申请一段和原对象一样大小的空间
- {
- strcpy(_str, s._str); // 把原对象的数据一一拷贝给新对象
- }
-
- // 赋值运算符重载构造
- String& operator=(const String& s)
- {
- if (this != &s) // 防止自己给自己赋值
- {
- char* pStr = new char[strlen(s._str) + 1]; // 重新开辟一块和s一样大小的空间
- delete[] _str; // 释放自己的空间
- _str = pStr;
- strcpy(pStr, s._str); // 把s的数据拷贝过来
- }
- return *this;
- }
-
- ~String()
- {
- if (_str)
- {
- delete[] _str;
- _str = nullptr;
- }
- }
- private:
- char* _str;
- };
所以我们先开辟空间,如果开辟空间没有失败,再去释放自己的空间。

传统写法和现代写法的区别:
- 传统写法:想要做深拷贝,都是自己去做,自己去开辟空间,自己去拷贝想要的内容。
- 现代写法:想要做深拷贝,不是自己去做,而是去构造一个的新的临时对象,临时对象中的内容就是自己想要的内容,然后将临时对象与当前对象的成员变量分别进行交换,这样当前的对象就拿到了自己想要的内容,当函数调用结束后,临时对象出了作用域就会被自动析构。
拷贝构造函数的深拷贝(现代写法):

赋值运算符重载函数的深拷贝(现代写法):

- class String
- {
- public:
- String(const char* str = "")
- {
- if (nullptr == str)
- {
- assert(false);
- return;
- }
- _str = new char[strlen(str) + 1];
- strcpy(_str, str);
- }
-
- // 拷贝构造函数
- String(const String& s)
- : _str(nullptr) // 当前对象是一个正在构造的对象,成员变量还未初始化,是一个随机值,所以先置空
- {
- String strTmp(s._str); // 拿s的内容,调用构造函数构造临时对象strTmp
- swap(_str, strTmp._str); // 将临时对象strTmp和当前对象的成员变量_str进行交换
- }
-
- // 写法一(更好)
- String& operator=(String s) //传值
- {
- // 传参时,调用拷贝构造函数,拷贝构造了一个string类对象s
-
- // 将拷贝构造出来的string类对象s和当前对象的成员变量_str进行交换
- swap(_str, s._str);
- return *this; // 返回当前对象
- }
-
- // 写法二
- //String& operator=(const String& s) // 传引用
- //{
- // if(this != &s) // 防止自己给自己赋值
- // {
- // String strTmp(s); // 拿s的内容,调用构造函数构造临时对象strTmp
- // swap(_str, strTmp._str); // 将临时对象strTmp 和当前对象的成员变量_str进行交换
- // }
- // return *this;
- //}
-
- ~String()
- {
- if (_str)
- {
- delete[] _str;
- _str = nullptr;
- }
- }
- private:
- char* _str;
- };
赋值运算符重载函数的深拷贝中的方法二的缺点:需要进行额外的判断和创建临时对象,增加了代码的复杂度和开销。
string 是对字符串进行管理的类。实际上就是一个管理字符数组的顺序表。

- #include
- #include
- #include
- using namespace std;
-
- namespace xyl
- {
- class string
- {
- public:
- // 迭代器
- typedef char* iterator;
- typedef const char* const_iterator;
- iterator begin() { return _str; } // 返回指向第一个字符的迭代器
- iterator end() { return _str + _size; } // 返回指向最后一个字符下一个字符的迭代器
- const_iterator begin() const { return _str; } // 返回指向第一个字符的迭代器
- const_iterator end() const { return _str + _size; } // 返回指向最后一个字符下一个字符的迭代器
-
-
- // 默认成员函数:
- string(const char* str = ""); // 默认构造函数
- void swap(string& s); // 交换两个对象的内容
- string(const string& s); // 拷贝构造函数(深拷贝)
- string& operator=(string s); // 赋值运算符重载(深拷贝)
- ~string(); // 析构函数
-
-
- // 访问元素([]运算符重载)
- char& operator[](size_t pos); // 可读可写
- const char& operator[](size_t pos) const; // 只读不能写
-
-
- // 容量操作:
- size_t size() const { return _size; } // 获取字符串有效元素个数
- size_t capacity() const { return _capacity; } // 获取字符串容量(有效字符的最大容量)
- void clear() { _str[0] = '\0'; _size = 0; } // 清空有效字符
- void reserve(size_t n); // 更改容量(capacity)的大小
- void resize(size_t n, char ch = '\0'); // 调整字符串有效字符的长度
-
-
- // 修改操作:
- string& insert(size_t pos, const char ch); // 在pos位置插入一个字符
- string& insert(size_t pos, const char* str); // 在pos位置插入一个字符串
- void push_back(const char ch); // 尾插一个字符
- void append(const char* str); // 在当前字符串末尾追加一个字符串
- string& operator+=(const char ch); // 当前字符串末尾追加一个字符
- string& operator+=(const char* str); // 当前字符串末尾追加一个字符串
- string& operator+=(const string& s); // 当前字符串末尾追加一个字符/字符串
- string& erase(size_t pos = 0, size_t len = npos); // 删除从pos位置开始的len个字符
-
-
- // String operations
- size_t find(char ch, size_t pos = 0) const; // 从pos位置开始查找字符,若找到,则返回该字符的下标,若没找到,则返回npos
- size_t find(const char* str, size_t pos = 0) const; // 从pos位置开始查找子串,若找到,则返回该子串首字符的下标,若没找到,则返回npos
- char* c_str() const { return _str; } // 返回指向 C 格式字符串的数组的指针
-
-
- private:
- char* _str; // 指向字符数组
- size_t _size; // 有效字符数
- size_t _capacity; // 有效字符容量,不包含最后作标识的'\0'
- static const size_t npos;
- };
-
- const size_t string::npos = -1;
- };
写时拷贝 就是一种拖延症,是在浅拷贝的基础之上增加了引用计数的方式来实现的。
推荐文章:
- 写时拷贝技术:C++ STL STRING的COPY-ON-WRITE技术-CSDN博客
- 写时拷贝在读取时的缺陷:C++的STD::STRING的“读时也拷贝”技术!-CSDN博客
- #pragma once
-
- #include
- #include
- using namespace std;
-
- namespace xyl
- {
- class string
- {
- public:
- typedef char* iterator;
-
- public:
- // 默认构造函数
- string(const char* str = "") // 空串并不是什么都没有,第一个字符为'\0'
- :_size(strlen(str))
- ,_capacity(_size)
- {
- _str = new char[_capacity + 1]; // +1是确保有足够的空间存储字符串,因为还需要额外的一个字节来存储'\0'
- strcpy(_str, str); // 拷贝数据
- }
-
- // 拷贝构造函数(深拷贝)
- // s2(s1)
- string(const string& s)
- :_str(nullptr) // 当前对象是一个正在构造的对象,成员变量还未初始化,是一个随机值,所以先置空
- ,_size(0)
- ,_capacity(0)
- {
- string tmp(s._str); // 拿s的内容,调用构造函数构造临时对象tmp
- this->swap(tmp); // 将临时对象tmp和当前对象的成员变量分别进行交换
- }
-
- // 赋值运算符重载(深拷贝)
- // s1 = s2
- string& operator=(string s)
- {
- this->swap(s); // 将拷贝构造的对象s和当前对象的成员变量分别进行交换
- return *this; // 返回当前对象
- }
-
- // 析构函数
- ~string()
- {
- delete[] _str;
- _str = nullptr;
- }
-
-
- // iterator
- iterator begin()
- {
- return _str;
- }
- iterator end()
- {
- return _str + _size;
- }
-
-
- // modify
- // 在pos位置上插入字符c,并返回该字符的位置
- // 在pos位置插入一个字符
- string& insert(size_t pos, const char ch)
- {
- assert(pos >= 0 && pos <= _size);
-
- if (_size == _capacity) // 先检查是否需要扩容
- {
- // 防止是空串"",容量为0,扩容失败
- size_t newcapacity = _capacity == 0 ? 4 : 2 * _capacity;
-
- reserve(newcapacity);
- }
- // 挪动字符
- for (size_t i = _size + 1; i > pos; i--) // 注意
- {
- _str[i] = _str[i - 1];
- }
- _str[pos] = ch; // 插入字符
- _size++; // 有效字符个数+1
-
- return *this;
- }
-
- // 在pos位置插入一个字符串
- string& insert(size_t pos, const char* str)
- {
- assert(pos >= 0 && pos <= _size);
-
- size_t len = strlen(str);
- if (_size + len >= _capacity) // 先检查是否需要扩容
- {
- reserve(_size + len);
- }
-
- // 挪动字符
- for (size_t i = _size + len; i >= pos + len; i--)
- {
- _str[i] = _str[i - len];
- }
- // 插入字符
- for (size_t i = 0; i < len; i++)
- {
- _str[pos++] = str[i];
- }
- _size += len; // 更新有效字符个数
-
- return *this;
- }
-
- void push_back(char c)
- {
- / *if (_size >= _capacity) // 先检查是否需要扩容
- {
- // 防止是空串"",容量为0,扩容失败
- size_t newcapacity = _capacity == 0 ? 4 : 2 * _capacity;
-
- reserve(newcapacity); // 扩2倍容
- }
- _str[_size] = c; // 尾插字符
- _size++; // 有效字符个数+1
- _str[_size] = '\0'; // 补上字符串结束标志'\0' */
-
- insert(_size, ch);
- }
-
- string& erase(size_t pos = 0, size_t len = npos)
- {
- assert(pos >= 0 && pos < _size);
-
- // 1. 从pos位置开始,后面的字符删除完,这是一个O(1)的操作
- if (len == npos || pos + len >= _size)
- {
- _str[pos] = '\0';
- _size = pos;
- }
- // 2. 从pos位置开始,后面的字符删除一部分,这是一个O(n)的操作
- else
- {
- strcpy(_str + pos, _str + pos + len);
- _size -= len;
- }
- return *this;
- }
-
-
- string& operator+=(const char c)
- {
- push_back(c);
- return *this;
- }
- string& operator+=(const char* str)
- {
- append(str);
- return *this;
- }
- string& operator+=(const string& s)
- {
- append(s._str);
- return *this;
- }
-
-
- void append(const char* str)
- {
- /* size_t len = strlen(str);
- if (_size + len > _capacity) // 先检查是否需要扩容
- {
- reserve(_size + len); // 扩容
- }
- strcpy(_str + _size, str); // 尾插字符串(strcpy会拷贝'\0',并在该点停止)
- _size += len; // 有效字符个数+len */
-
- insert(_size, str);
- }
-
-
- void clear()
- {
- _size = 0;
- _str[_size] = '\0';
- }
-
-
- // s1.swap(s2);
- void swap(string& s)
- {
- // 函数名冲突,指定去调用全局域里面的::swap
- ::swap(_str, s._str);
- ::swap(_size, s._size);
- ::swap(_capacity, s._capacity);
- }
-
-
- // capacity
- size_t size()const
- {
- return _size;
- }
- size_t capacity()const
- {
- return _capacity;
- }
- bool empty()const
- {
- return 0 == _size;
- }
-
-
- // 调整字符串有效字符的长度
- void resize(size_t n, char ch = '\0')
- {
- // 要调整的有效字符的长度小于原有_size大小
- if (n < _size)
- {
- _size = n; // 更新有效字符个数
- _str[_size] = '\0'; // 补上字符串结束标志'\0'
- }
- // 要调整的有效字符的长度大于原有_size大小
- else if (n > _size)
- {
- // 要调整的有效字符的长度大于原有_capacity大小,先进行增容
- if (n > _capacity) reserve(n);
-
- // 多出的位置用字符ch(缺省值'\0')进行填充
- for (size_t i = _size; i < n; i++)
- {
- _str[i] = ch;
- }
- _size = n; // 更新有效字符个数
- _str[_size] = '\0'; // 补上字符串结束标志'\0'
- }
- }
-
-
- // 更改容量(capacity)的大小
- void reserve(size_t n)
- {
- if (n > _capacity) // 如果新容量大于旧容量,则开辟空间
- {
- // 开辟新空间
- char* tmp = new char[n + 1];
- strcpy(tmp, _str); // 旧空间数据拷贝到新空间
-
- // 释放旧空间,使用新空间
- delete[] _str;
- _str = tmp; // 指向新空间
- _capacity = n; // 更新容量
- }
- }
-
-
- // access
- char& operator[](size_t index) // 用于访问字符串中指定位置的字符
- {
- assert(index < _size);
- return _str[index];
- }
-
-
- // 普通版本和const版本
- char& operator[](size_t pos) // 可读可写
- {
- assert(pos < _size);
- return _str[pos]; // *(_str + pos)
- }
- const char& operator[](size_t pos) const // 只读不能写
- {
- assert(pos < _size);
- return _str[pos]; // *(_str + pos)
- }
-
-
- // 比较两个对象的大小(按字符ascii码比较)
- // s1 > s2
- bool operator>(const string& s1, const string& s2)
- {
- // 指针 i 和 j 分别指向两个字符串的第一个字符
- size_t i = 0, j = 0;
- for (; i < s1.size() && j < s2.size(); i++, j++) // 同时遍历两个字符串
- {
- if (s1[i] != s2[j]) return s1[i] > s2[j];
- }
-
- if (i == s1.size() && j == s2.size()) return false; // 同时被遍历完,说明 s1 = s2
- else if (i == s1.size()) return false; // s1先被遍历完,说明 s1 < s2
- else if (j == s2.size()) return true; // s2先被遍历完,说明 s1 > s2
- }
-
- // s1 == s2
- bool operator==(const string& s1, const string& s2)
- {
- // 指针 i 和 j 分别指向两个字符串的第一个字符
- size_t i = 0, j = 0;
- for (; i < s1.size() && j < s2.size(); i++, j++) // 同时遍历两个字符串
- {
- if (s1[i] != s2[j]) return false;
- }
-
- if (i == s1.size() && j == s2.size()) return true; // 同时被遍历完,说明 s1 = s2
- else return false; // 有一个字符串没被遍历完
- }
-
- // 下面的关系运算符重载,全都可以复用上面的代码
- // s1 != s2
- bool operator!=(const string& s1, const string& s2) { return !(s1 == s2); }
- // s1 >= s2
- bool operator>=(const string& s1, const string& s2) { return s1 > s2 || s1 == s2; }
- // s1 < s2
- bool operator<(const string& s1, const string& s2) { return !(s1 >= s2); }
- // s1 <= s2
- bool operator<=(const string& s1, const string& s2) { return !(s1 > s2); }
-
-
- // 返回c在string中第一次出现的位置
- size_t find(char c, size_t pos = 0) const
- {
- assert(pos >= 0 && pos < _size);
-
- for (size_t i = pos; i < _size; i++)
- {
- if (_str[i] == c) return i;
- }
- return npos;
- }
-
- // 返回子串s在string中第一次出现的位置
- size_t find(const char* s, size_t pos = 0) const
- {
- assert(pos >= 0 && pos < _size);
-
- // 在原串中去匹配子串s
- // 匹配成功,返回子串s首字符的地址
- // 匹配失败,返回空指针
- const char* p = strstr(_str + pos, s);
-
- if (p) return p - _str; // 通过子串s首字符的地址,计算出首字符的下标
- else return npos;
- }
-
- private:
- friend ostream& operator<<(ostream& _cout, const xyl::string& s);
- friend istream& operator>>(istream& _cin, xyl::string& s);
- private:
- char* _str;
- size_t _capacity;
- size_t _size;
- };
-
- ostream& operator<<(ostream& _cout, const xyl::string& s)
- {
- // 不能使用cout, 因为string的字符串内部可能会包含\0
- // 直接cout时, 是将_str当成char*打印的,遇到内部的\0时后序内容就不打印了
- //cout << s._str;
- for (size_t i = 0; i < s.size(); ++i)
- {
- _cout << s[i];
- }
- return _cout;
- }
-
- istream& operator>>(istream& _cin, string& s)
- {
- // 一个一个字符输入
- // 遇到空格或者换行符终止输入
- char c;
- _cin >> c; // 从流中获取一个字符
- while (c != ' ' && c != '\n')
- {
- s += c; // 把提取的字符追加到sting类对象s中去
- _cin >> c; // 继续从流中获取下一个字符
- }
- return _cin;
- }
- }
-
-
- int main()
- {
- xyl::string s1("hello");
- s1.push_back(' ');
- s1.push_back('w');
- s1.push_back('o');
- s1.push_back('r');
- s1 += 'l';
- s1 += 'd';
- cout << s1 << endl; //hello world
- cout << s1.size() << endl; //11
- cout << s1.capacity() << endl; //20
-
- // 利用迭代器打印string中的元素
- xyl::string::iterator it = s1.begin();
- while (it != s1.end())
- {
- cout << *it;
- ++it;
- }
- cout << endl;
-
- // 这里可以看到一个类只要支持的基本的iterator,就支持范围for
- for (auto ch : s1)
- {
- cout << ch;
- }
- cout << endl;
- return 0;
- }