一、标准库中的string类
1、 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;
2、string类的常用接口说明(注意下面我只讲解最常用的接口)
1)string类对象的常见构造
//string 类的四种构造
int main()
{
string s1;//构造空的string类对象s1
string s2("hello");//用C格式字符串构造string类对象s2
string s3(10, '$');//输出10个$的符号
string s4(s2);//拷贝构造s4
cin >> s1;
cout << s1 << endl;//anmo
cout << s2 << endl;//hello
cout << s3 << endl; //$$$$$$$$$$
cout << s4 << endl;//hello
system("pause");
return 0;
}
2)string类对象的容量操作
-
size、length、capacity、clear、resize
//size:返回字符串有效字符的长度 //length:返回字符串有效字符的长度 //capacity:返回空间总大小 //empty:检测字符串释放为空串,是返回true,否则返回false //clear:清空有效字符 //resize:将有效字符的个数改成n个,多出的空间用字符c填充 int main() { //注意:string类对象支持直接用cin和cout进行输入和输出 string s("hello anmo!"); cout << s.size() << endl;//11 cout << s.length() << endl;//11 cout << s.capacity() << endl;//15 cout << s << endl;//hello anmo! //将s中字符串清空,注意清空时只是将size清0,不改变低层空间大小 s.clear(); cout << s.size() << endl;//0 cout << s.length() << endl;//0 cout << s.capacity() << endl;//15 //将s中有效字符个数增加到10个,都出的位置用'!'进行填充 //resize功能:改变string中有效字符的个数 //1、将有效字符个数增加到n个:多出的位置需要用c来补充(可能需要扩容) //2、将有效字符个数减少到n个:只修改有效字符的个数不会缩小空间 string s1("anmo"); cout << s1.size() << endl;//4 cout << s1.length() << endl;//4 cout << s1.capacity() << endl;//15 cout << s1 << endl;//anmo s1.resize(10, '!'); cout << s1.size() << endl;//10 cout << s1.length() << endl;//10 cout << s1.capacity() << endl;//15 cout << s1 << endl;//anmo!!!!!! s1.resize(15); cout << s1.size() << endl;//15 cout << s1.length() << endl;//15 cout << s1.capacity() << endl;//15 cout << s1 << endl;//anmo!!!!!! s1.resize(2);//将有效字符个数减少到5个 cout << s1.size() << endl;//2 cout << s1.length() << endl;//2 cout << s1.capacity() << endl;//15 cout << s1 << endl;//an system("pause"); return 0; }
-
reserve
//void reserve(size_t n);改变低层容量的大小,不会修改有效字符的个数 //1、扩大容量:n<=旧容量大小 不会扩容 // n>旧空间大小 扩容 //2、缩小容量:n>最初默认空间大小 不会缩小 // n<=最初默认空间大小 缩小容量 //利用reserve提高插入数据的效率,避免增容带来的开销 int main() { string s("anmo"); s.reserve(10); cout << s.size() << endl;//4 cout << s.capacity() << endl;//15 s.reserve(15); cout << s.size() << endl;//4 cout << s.capacity() << endl;//15 s.reserve(40); cout << s.size() << endl;//4 cout << s.capacity() << endl;//47 s.reserve(80); cout << s.size() << endl;//4 cout << s.capacity() << endl;//95 s.reserve(30); cout << s.size() << endl;//4 cout << s.capacity() << endl;//95 s.reserve(16); cout << s.size() << endl;//4 cout << s.capacity() << endl;//95 s.reserve(8); cout << s.size() << endl;//4 cout << s.capacity() << endl;//15 system("pause"); return 0; }
注意:
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的底层空间总大小时,reserve不会改变容量大小。
3)string类对象的访问及遍历操作
void Teststring()
{
string s1("hello anmo");
const string s2("hello anmo");
cout << s1 << " " << s2 << endl;//hello anmo hello anmo
cout << s1[0] << " " << s2[0] << endl;//h h
s1[0] = 'H';
cout << s1 << endl;//Hello anmo
//s2[0]='H';//代码编译失败,因为const类型对象不能修改
}
void TestString()
{
string s("hello Bit");
// 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();
while (rit != s.rend())
{
cout << *rit << endl;
}
// 3.范围for
for (auto ch : s)
{
cout << ch << endl;
}
}
4)string类对象的修改操作
-
reverse逆转
int main() { string s("anmo"); cout << s << endl;//anmo reverse(s.begin(), s.end()); cout << s << endl;//omna system("pause"); return 0; }
-
append添加
int main() { string s("I"); string s2(" anmo "); s+= " love "; cout << s << endl;//I love s += " you "; cout << s << endl;//I love you s.append(s2); cout << s << endl;//I love you anmo s.append("!!!"); cout << s << endl;//I love you anmo!!! system("pause"); return 0; }
-
insert插入
int main() { string s("IYOU"); s.insert(1, " LOVE "); cout << s << endl;//I LOVE YOU system("pause"); return 0; }
-
erase清除 find查找
int main() { string s("hello anmo"); cout << s << endl;//hello anmo s.erase(s.begin() + s.find(" "), s.end()); cout << s << endl;//hello // 获取file的后缀 string s1("hauhduadh.txt"); cout << s1 << endl;//hauhduadh.txt s1.erase(s1.begin() + s1.find("."), s1.end()); cout << s1 << endl;//hauhduadh system("pause"); return 0; }
-
substr截取 rfind反向查找
int main() { string s("anmo.txt"); cout << s << endl;//anmo.txt cout << s.substr(s.rfind(".") + 1) << endl;//txt string s1("https://www.duba.com/?f=qlswdhq&tjiedb=1&ft=gjlock&--type=0"); int ret = s1.find(" : ") + 3; cout << s1.substr(ret, s1.find("/", ret)-ret) << endl;//www.duba.com system("pause"); return 0; }
-
push_back、append
int main() { string s; s.push_back('I');//在s后插入I cout << s << endl;//I s.append(" Love ");//在s后追加一个字符串"Love" cout << s << endl;//I Love s += " you "; // 在s后追加一个字符串'you' cout << s << endl;//I Love you s += " anmo ";// 在s后追加一个字符串"anmo" cout << s << endl;//I Love you anmo s += '!';//在s后追加一个字符'!' cout << s << endl;//I Love you anmo ! //获取file后缀 string file("anmo.txt"); size_t pos = file.rfind('.'); cout << file.substr(pos+1, file.size() - pos) << endl;//txt system("pause"); return 0; }
注意:
- 在string尾部追加字符时,s.push_back© / s.append(1, c) / s += 'c’三种的实现方式差不多,一般 情况下string类的+=操作用的比较多,+=操作不仅可以连接单个字符,还可以连接字符串。
- 对string操作时,如果能够大概预估到放多少字符,可以先通过reserve把空间预留好。
二、 string类的模拟实现
1、 经典的string类问题
class string
{
public:
/*string()
:_str(new char[1])
{*_str = '\0';}
*/
//string(const char* str = "\0") 错误示范
//string(const char* str = nullptr) 错误示范
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 bit!!!");
string s2(s1);
}
说明:上述string类没有显式定义其拷贝构造函数与赋值运算符重载,此时编译器会合成默认的,当用s1构 造s2时,编译器会调用默认的拷贝构造。最终导致的问题是,s1、s2共用同一块内存空间,在释放时同一块空间被释放多次而引起程序崩溃,这种拷贝方式,称为浅拷贝。
2、浅拷贝深拷贝
- 浅拷贝:也称位拷贝,编译器只是将对象中的值拷贝过来。如果对象中管理资源,最后就会导致多个对象共享同一份资源,当一个对象销毁时就会将该资源释放掉,而此时另一些对象不知道该资源已经被释放,以为还有效,所以 当继续对资源进项操作时,就会发生发生了访问违规。要解决浅拷贝问题,C++中引入了深拷贝。
- 深拷贝:如果一个类中涉及到资源的管理,其拷贝构造函数、赋值运算符重载以及析构函数必须要显式给出。一般情况都是按照深拷贝方式提供。
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;
};
3、写时拷贝
写时拷贝就是一种拖延症,是在浅拷贝的基础之上增加了引用计数的方式来实现的。
引用计数:用来记录资源使用者的个数。在构造时,将资源的计数给成1,每增加一个对象使用该资源,就给计数增加1,当某个对象被销毁时,先给该计数减1,然后再检查是否需要释放资源,如果计数为1,说明该对象时资源的最后一个使用者,将该资源释放;否则就不能释放,因为还有其他对象在使用该资源。