目录

在C语言中,字符串是以‘\0’结尾的一些字符的集合,为了操作方便,C标准库中提供了一些str系列的库函数,但是这些库函数与字符串时分离开的,不太符合OOP的思想,而且底层空间需要用户自己管理,稍不留神可能还会越界访问。
OOP -> Object Oriented Programming(面向对象程序设计)是一种计算机编程架构。OOP 的一条基本原则是计算机程序是由单个能够起到子程序作用的单元或对象组合而成。
核心思想:封装、继承、多态。
使用OOP的好处:
- 易维护
- 质量高
- 效率高
- 易扩展

总结:
在使用string类时,必须包括#include头文件以及using namespace std;
| 函数名称 | 功能说明 |
| string() |
构造空的string类对象,即空字符串
|
| string(const char* s) |
用C-string来构造string类对象
|
| string(size_t n, char c) |
string类对象中包含n个字符c
|
| string(const string& s) |
拷贝构造函数
|
- #include <iostream>
- using namespace std;
-
- void Teststring()
- {
- string s1; // 构造空的string类对象s1
- string s2("hello bit"); // 用C格式字符串构造string类对象s2
- string s3(s2); // 拷贝构造s3
- }
-
- int main()
- {
-
- return 0;
- }
2. string类对象的容量操作
| 函数名称 | 功能说明 |
| size | 返回字符串有效字符长度 |
| length | 返回字符串有效字符长度 |
| capacity | 返回空间总大小 |
| empty | 检测字符串释放为空串,是返回true,否则返回false |
| clear | 清空有效字符 |
| reserve | 为字符串预留空间 |
| resize | 将有效字符的个数改成n个,多出空间用字符c填充 |
- #define _CRT_SECURE_NO_WARNINGS
-
- #include <iostream>
- #include <string>
- using namespace std;
-
-
- // 测试string容量相关的接口
- // size/clear/resize
- void Teststring1()
- {
- // 注意:string类对象支持直接用cin和cout进行输入和输出
- string s("hello, world");
-
- cout << s.size() << endl;
- cout << s.length() << endl;
- cout << s.capacity() << endl;
- cout << s << endl;
-
- // 将s中的字符串清空,注意清空时只是将size清0,不改变底层空间的大小
- s.clear();
-
- cout << s.size() << endl;
- cout << s.capacity() << endl;
-
- // 将s中有效字符个数增加到10个,多出位置用'a'进行填充
- // “aaaaaaaaaa”
- s.resize(10, 'a');
-
- cout << s.size() << endl;
- cout << s.capacity() << endl;
-
- // 将s中有效字符个数增加到15个,多出位置用缺省值'\0'进行填充
- // "aaaaaaaaaa\0\0\0\0\0"
- // 注意此时s中有效字符个数已经增加到15个
- s.resize(15);
-
- cout << s.size() << endl;
- cout << s.capacity() << endl;
- cout << s << endl;
-
- // 将s中有效字符个数缩小到5个
- s.resize(5);
-
- cout << s.size() << endl;
- cout << s.capacity() << endl;
- cout << s << endl;
- }
-
- //====================================================================================
- void Teststring2()
- {
- string s;
- // 测试reserve是否会改变string中有效元素个数
- s.reserve(100);
-
- cout << s.size() << endl;
- cout << s.capacity() << endl;
-
- // 测试reserve参数小于string的底层空间大小时,是否会将空间缩小
- s.reserve(50);
-
- cout << s.size() << endl;
- cout << s.capacity() << endl;
- }
-
- // 利用reserve提高插入数据的效率,避免增容带来的开销
- //====================================================================================
- 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';
- }
- }
- }
-
- // 构建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';
- }
- }
- }
-
- int main()
- {
- return 0;
- }
注意:
3. string类对象的访问及遍历操作
| 函数名称 | 功能说明 |
| operator[] | 返回pos位置的字符,const string类对象调用 |
| begin + end | huoqbegin获取一个字符的迭代器 + end获取最后一个字符下一个位置的迭代器 |
| rbegin + rend | huoqbegin获取一个字符的迭代器 + end获取最后一个字符下一个位置的迭代器 |
| 范围for | C++11支持更简洁的范围for的新遍历方式 |
- #define _CRT_SECURE_NO_WARNINGS
-
- #include <iostream>
- #include <string>
- using namespace std;
-
- // string的遍历
- // begin()+end() for+[] 范围for
- // 注意:string遍历时使用最多的还是for+下标 或者 范围for(C++11后才支持)
- // begin()+end()大多数使用在需要使用STL提供的算法操作string时,比如:采用reverse逆置string
- void Teststring3()
- {
- 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类型对象不能修改
- }
-
- void Teststring4()
- {
- string s("hello world");
- // 3种遍历方式:
- // 需要注意的以下三种方式除了遍历string对象,还可以遍历是修改string中的字符,
- // 另外以下三种方式对于string而言,第一种使用最多
- // 1. for+operator[]
- for (size_t i = 0; i < s.size(); ++i)
- cout << s[i] << endl;
-
- // 2.迭代器
- string::iterator it = s.begin();
-
- while (it != s.end())
- {
- cout << *it << endl;
- ++it;
- }
-
- // string::reverse_iterator rit = s.rbegin();
- // C++11之后,直接使用auto定义迭代器,让编译器推到迭代器的类型
- auto rit = s.rbegin();
- while (rit != s.rend())
- cout << *rit << endl;
-
- // 3.范围for
- for (auto ch : s)
- cout << ch << endl;
- }
-
- int main()
- {
- return 0;
- }
4. string类对象的修改操作
| 函数名称 | 功能说明 |
| push_back | 在字符串后尾插字符c |
| append | 在字符串后追加一个字符串 |
| operator+= | 在字符串后追加字符串str |
| c_str | 返回c格式字符串 |
| find + npos | 从字符串pos位置开始往后找字符c,返回该字符在字符串中的位置 |
| rfind | 从字符串pos位置开始往前找字符c,返回该字符在字符串中的位置 |
| substr | 在str中从pos位置开始,截取n个字符,然后将其返回 |
- #define _CRT_SECURE_NO_WARNINGS
-
- #include <iostream>
- #include <string>
- using namespace std;
-
- // 测试string:
- // 1. 插入(拼接)方式:push_back append operator+=
- // 2. 正向和反向查找:find() + rfind()
- // 3. 截取子串:substr()
- // 4. 删除:erase
- void Teststring5()
- {
- string str;
-
- str.push_back(' '); // 在str后插入空格
- str.append("hello"); // 在str后追加一个字符"hello"
- str += 'b'; // 在str后追加一个字符'b'
- str += "it"; // 在str后追加一个字符串"it"
-
- cout << str << endl;
- cout << str.c_str() << endl; // 以C语言的方式打印字符串
-
- // 获取file的后缀
- string file("string.cpp");
- size_t pos = file.rfind('.');
- string suffix(file.substr(pos, file.size() - pos));
-
- cout << suffix << endl;
-
- // npos是string里面的一个静态成员变量
- // static const size_t npos = -1;
-
- // 取出url中的域名
- string url("http://www.cplusplus.com/reference/string/string/find/");
-
-
- cout << url << endl;
- 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;
-
- // 删除url的协议前缀
- pos = url.find("://");
- url.erase(0, pos + 3);
-
- cout << url << endl;
- }
-
- int main()
- {
- return 0;
- }
注意:
5. string类非成员函数
| 函数 | 功能说明 |
| operator+ | 尽量少用,因为传值返回,导致深拷贝效率低 |
| operator>> | 输入运算符重载 |
| operator<< | 输出运算符重载 |
| getline | 获取一行字符串 |
| relational operators | 大小比较 |
6. vs和g++下string结构的说明
注意:下述结构是在32位平台下进行,32位平台下指针占4个字节。
string总共占28个字节,内部结构稍微复杂一点,先是有一个联合体,联合体用来定义string中字符串的存储空间:
- 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;
这种设计也是有一定道理的,大多数情况下字符串的长度都小于16,那string对象创建好后,内部已经有了16个字符数组的固定空间,不需要通过堆创建,效率高。
其次:还有一个size_t字段保存字符串长度,一个size_t字段保存从堆上开辟空间总的容量。
最后:还有一个指针做一些其他事情。
故总共占16 + 4 + 4 + 4 = 28个字节。

g++下,string是通过写时拷贝实现的,string对象总共占4个字节,内部只包含了一个指针,该指针将来指向一块堆空间,内部包含了如下字段:
- struct _Rep_base
- {
- size_type _M_length;
- size_type _M_capacity;
- _Atomic_word _M_refcount;
- };
模拟实现string类,最主要是实现string类的构造、拷贝构造、赋值运算符重载以及析构函数。
- #define _CRT_SECURE_NO_WARNINGS
-
- #include <iostream>
- #include <string>
- #include <cassert>
- using namespace std;
-
- 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()
- {
- if (_str)
- {
- delete[] _str;
-
- _str = nullptr;
- }
- }
-
- private:
- char* _str;
- };
-
- void TestString()
- {
- String s1("hello world");
-
- String s2(s1);
- }
浅拷贝:
也称位拷贝,编译器只是将对象中的值拷贝过来。如果对象中管理资源,最后就会导致多个对象共享同一份资源,当一个对象销毁时就会将该资源释放,而此时另一些对象不知道该资源已经被释放,以为还有效,所以当继续对资源进项操作时,就会发生访问违规。
可以采用深拷贝解决浅拷贝问题,即:每个对象都有一份独立的资源,不要和其他对象共享。
如果一个类中涉及到资源的管理,其拷贝构造函数,赋值运算符重载以及构造函数必须要显式给出。一般情况都是按照深拷贝方式提供。

- #define _CRT_SECURE_NO_WARNINGS
-
- #include <iostream>
- #include <string>
- #include <cassert>
- using namespace std;
-
- 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];
-
- strcpy(pStr, s._str);
-
- delete[] _str;
- _str = pStr;
- }
-
- return *this;
- }
-
- ~String()
- {
- if (_str)
- {
- delete[] _str;
-
- _str = nullptr;
- }
- }
-
- private:
- char* _str;
- };
- #define _CRT_SECURE_NO_WARNINGS
-
- #include
- #include
- #include
- using namespace std;
-
- 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);
-
- swap(_str, strTmp._str);
- }
-
- String& operator=(String s)
- {
- swap(_str, s._str);
-
- return *this;
- }
-
- ~String()
- {
- if (_str)
- {
- delete[] _str;
-
- _str = nullptr;
- }
- }
- private:
- char* _str;
- };
写时拷贝就是一种拖延症,实在浅拷贝的基础之上增加了引用计数的方式来实现的。
引用计数:用来记录资源使用者的个数。在构造时,将资源的计数给成1,每增加一个对象使用该资源,就给计数增加1,当某个对象被销毁时,先给该计数减1,然后再检查是否需要释放资源,如果计数为1,说明该对象是资源的最后一个使用者,将该资源释放;否则就不能释放,因为还有其他对象在使用该资源。
- #define _CRT_SECURE_NO_WARNINGS
-
- #include <iostream>
- #include <assert.h>
- using namespace std;
-
- namespace fyd
- {
- class string
- {
- public:
- typedef char* iterator;
-
- public:
- string(const char* str = "")
- {
- _size = strlen(str);
- _capacity = _size;
- _str = new char[_capacity + 1];
- strcpy(_str, str);
- }
-
- string(const string& s)
- : _str(nullptr)
- , _size(0)
- , _capacity(0)
- {
- string tmp(s._str);
- this->swap(tmp);
- }
-
- string& operator=(string s)
- {
- this->swap(s);
- return *this;
- }
-
- ~string()
- {
- if (_str)
- {
- delete[] _str;
- _str = nullptr;
- }
- }
-
- iterator begin()
- {
- return _str;
- }
-
- iterator end()
- {
- return _str + _size;
- }
-
- void push_back(char c)
- {
- if (_size == _capacity)
- reserve(_capacity * 2);
-
- _str[_size++] = c;
- _str[_size] = '\0';
- }
-
- string& operator+=(char c)
- {
- push_back(c);
- return *this;
- }
-
- void append(const char* str)
- {
- size_t len = strlen(str);
- if ((_size + len) > _capacity)
- {
- reserve(_size + len);
- }
-
- strcpy(_str + _size, str);
- _size += len;
- }
-
- string& operator+=(const char* str)
- {
- append(str);
- return *this;
- }
-
- void clear()
- {
- _size = 0;
- _str[_size] = '\0';
- }
-
- void swap(string& s)
- {
- std::swap(_str, s._str);
- std::swap(_size, s._size);
- std::swap(_capacity, s._capacity);
- }
-
- const char* c_str()const
- {
- return _str;
- }
-
- size_t size()const
- {
- return _size;
- }
-
- size_t capacity()const
- {
- return _capacity;
- }
-
- bool empty()const
- {
- return 0 == _size;
- }
-
- void resize(size_t newSize, char c = '\0')
- {
- if (newSize > _size)
- {
- // 如果newSize大于底层空间大小,则需要重新开辟空间
- if (newSize > _capacity)
- {
- reserve(newSize);
- }
-
- memset(_str + _size, c, newSize - _size);
- }
-
- _size = newSize;
- _str[newSize] = '\0';
- }
-
- void reserve(size_t newCapacity)
- {
- // 如果新容量大于旧容量,则开辟空间
- if (newCapacity > _capacity)
- {
- char* str = new char[newCapacity + 1];
-
- strcpy(str, _str);
-
- // 释放原来旧空间,然后使用新空间
- delete[] _str;
- _str = str;
- _capacity = newCapacity;
- }
- }
-
- // access
- char& operator[](size_t index)
- {
- assert(index < _size);
-
- return _str[index];
- }
-
- const char& operator[](size_t index)const
- {
- assert(index < _size);
-
- return _str[index];
- }
-
- bool operator<(const string& s)
- {
- return strcmp(_str, s._str) < 0;
- }
-
- bool operator==(const string& s)
- {
- return strcmp(_str, s._str) == 0;
- }
-
- bool operator<=(const string& s)
- {
- return ((_str < s._str) || (_str == s._str));
- }
-
- bool operator>(const string& s)
- {
- return !((_str < s._str) || (_str == s._str));
- }
-
- bool operator>=(const string& s)
- {
- return !(strcmp(_str, s._str) < 0);
- }
-
- bool operator!=(const string& s)
- {
- return !(strcmp(_str, s._str) == 0);
- }
-
- // 返回c在string中第一次出现的位置
- size_t find(char c, size_t pos = 0) const
- {
- for (size_t i = pos; i < _size; i++)
- {
- if (_str[i] == c)
- return i;
- }
-
- return -1;
- }
-
- // 返回子串s在string中第一次出现的位置
- size_t find(const char* s, size_t pos = 0) const
- {
- const char* ret = strstr(_str + pos, s);
-
- if (ret)
- return ret - _str;
- return -1;
- }
-
- // 在pos位置上插入字符c/字符串str,并返回该字符的位置
- string& insert(size_t pos, char c)
- {
- if (_size == _capacity)
- {
- reserve(_capacity == 0 ? 4 : _capacity * 2);
- }
-
- char* end = _str + _size;
- while (end > _str + pos)
- {
- *(end + 1) = *end;
- --end;
- }
- _str[pos] = c;
- _size++;
-
- return *this;
- }
- string& insert(size_t pos, const char* str)
- {
- size_t len = strlen(str);
-
- if ((_size + len) > _capacity)
- {
- reserve(_size + len);
- }
-
- char* end = _str + _size;
- while (end > (_str + pos))
- {
- *(end + len) = *end;
- --end;
- }
-
- strncpy(_str + pos, str, len);
- _size += len;
-
- return *this;
- }
-
- // 删除pos位置上的元素,并返回该元素的下一个位置
- string& erase(size_t pos, size_t len)
- {
- size_t leftNum = _size - pos;
-
- if (len >= leftNum)
- {
- _str[pos] = '\0';
- _size = pos;
- }
- else
- {
- strcpy(_str + pos, _str + pos + len);
- _size -= len;
- }
-
- return *this;
- }
-
- private:
- friend ostream& operator<<(ostream& _cout, const fyd::string& s);
- friend istream& operator>>(istream& _cin, fyd::string& s);
- private:
- char* _str;
- size_t _capacity;
- size_t _size;
- };
-
- ostream& operator<<(ostream& _cout, const fyd::string& s)
- {
- for (size_t i = 0; i < s.size(); ++i)
- {
- _cout << s[i];
- }
- return _cout;
- }
-
- istream& operator>>(istream& _cin, string& s)
- {
- s.clear();
- char ch;
-
- ch = _cin.get();
- while (ch != ' ' && ch != '\n')
- {
- s += ch;
-
- ch = _cin.get();
- }
-
- return _cin;
- }
- }
-
- ///对自定义的string类进行测试
- void TestString()
- {
- fyd::string s1("hello");
-
- s1.push_back(' ');
- s1.push_back('w');
- s1.push_back('o');
- s1.push_back('r');
- s1.push_back('l');
-
- s1 += 'd';
-
- cout << s1 << endl;
- cout << s1.size() << endl;
- cout << s1.capacity() << endl;
-
- // 利用迭代器打印string中的元素
- fyd::string::iterator it = s1.begin();
- while (it != s1.end())
- {
- cout << *it;
- ++it;
- }
-
- cout << endl;
-
- // 这里可以看到一个类只要支持的基本的iterator,就支持范围for
- for (auto ch : s1)
- cout << ch;
- cout << endl;
- }
-
- int main()
- {
-
- TestString();
-
- return 0;
- }
感谢大佬们的支持!!!
互三啦!!!