STL_STRING
1.为什么要学习string类
1.1C语言中,字符串是以’\0’结尾的一些字符的集合,为了操作方便,C标准库中提供了一些str系列的库函数,但是这些库函数与字符串是分离开的,不太符合OOP( 面向对象编程(Object Oriented Programming,OOP,面向对象程序设计)是一种计算机编程架构)的思想。而且底层空间需要用户自己管理。稍不留神可能还会越界访问。
2.标准库中的string类
2.1string类
1.字符串是表示字符序列的类
2.标准的字符串类提供了对此类对象的支持,其接口类似于标准字符容器的接口,但添加了专门用于操作
单字节字符字符串的设计特性。
3.string类是使用char(即作为它的字符类型,使用它的默认char_traits和分配器类型(关于模板的更多信
息,请参阅basic_string)。
4.string类是basic_string模板类的一个实例,它使用char来实例化basic_string模板类,并用char_traits
和allocator作为basic_string的默认参数(根于更多的模板信息请参考basic_string)。
注意,这个类独立于所使用的编码来处理字节:如果用来处理多字节或变长字符(如UTF-8)的序列,这个
类的所有成员(如长度或大小)以及它的迭代器,将仍然按照字节(而不是实际编码的字符)来操作。
总结:
1.string是表示字符串的字符串类
2.该类的借口与常规容器的接口基本相同,再添加了一些专门用来操作string的常规操作。
3.string在底层实际是:basic_string模板类的别名,typedef basic_string<char, char_traits, allocator> string;
4.不能操作多字节或者变长字符的序列.
在 使用string类时,必须包含#include头文件以及using namespace std;
2.2string类的常用接口说明
1.string类对象的常见构造
//string入门
/void main()
{
//C数组
char str1[] = { 'a', 'b', 'c', '\0' };
cout << str1 << endl;
char *str2 = "bit";
cout << str2 << endl;
string str3("abc");
cout << "str1 len=" << strlen(str1) << endl;
cout << "str3 len=" << str3.size() << endl;
cout << "str3 len=" << str3.length() << endl;
}
1.string()构造空的string类对象,即空字符串
//string()
string str1;//构造一个空串
cout << str1 << endl;
2.用C-string来构造string类对象
//string(const char* s)
const char *s = "Hello world";//用Cstring构造string类对象
//string str2(s);
cout << "str2 = " << str2 << endl;
3.string类对象中包含n个字符c
//string(size_t n,char *s)
string str4(10, 'a');//string类对象中包括n个字符a
cout << "str4 = " << str4 << endl;
4.拷贝构造函数
//string(const string&s)
string str5(str3);//拷贝构造
cout << "str5 = " << str5 << endl;
2.string类对象的容量操作
string str("Hello world");
cout << "size = " << str.size() << endl;//字符串的有效大小 不包含\0
cout << "length = " << str.length() << endl;//字符串的有效长度
cout << "capacity = " << str.capacity() << endl;
cout << "empty = " << str.empty() << endl;//检测是否为空
str.clear();//将str中的字符串清空,注意清空时只是将size清0,不改变底层空间的大小
cout << "size = " << str.size() << endl;
cout << "capacity = " << str.capacity() << endl;//底层开辟的空间
const char *str2 = "Hello";
string str3(str2);
str3.resize(10, 'b');// 将s中有效字符个数增加到10个,多出位置用'b'进行填充,可增加可缩小
cout << "str3 = " << str3 << endl;
str3.reserve(100);//
cout << "size = " << str3.size() << endl;
cout << "capacity = " << str3.capacity() << endl;
//测试reserve参数小于string的底层空间大小时,是否会将空间缩小
str3.reserve(50);
cout << "size = " << str3.size() << endl;
cout << "capacity = " << str3.capacity() << endl;
总结:
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在改变元素个数时,如果是将元素个数增多,可能会改变底层容量的大
小,如果是将元素个数减少,底层空间总大小不变
- reserve(size_t res_arg=0):为string预留空间,不改变有效元素个数,当reserve的参数小于
string的底层空间总大小时,reserver不会改变容量大小
-
string类对象的访问及遍历操作
void main() { string str = "hello world"; cout << "str = " << str << endl;//直接输出 //operator[] 底层实现了这个类 for (int i = 0; i < str.size(); i++) cout << str[i]; cout << endl; //C++11输出方法 底层实现迭代器++ for (auto &e : str)//用引用属于别名 改str内容就是底层改变,不用&只改变了值,需要重新开辟空间,效率大大降低. cout << e; cout << endl; //迭代器 iteraror string::iterator it = str.begin();//区间内容 while (it != str.end()) { cout << *it; ++it; } cout << endl; //反向迭代器 /*string::reverse_iterator rit = str.rbegin();//反向输出 while(rit != str.rend()) { cout << *rit; ++rit; } cout << endl; }
-
string类对象的修改操作
push_back
在字符串后尾插字符c
append
在字符串后追加一个字符串
operator+= (重点)
在字符串后追加字符串str
c_str(重点)
返回C格式字符串
fifind + npos(重点)
从字符串pos位置开始往后找字符c,返回该字符在字符串中的位置
rfifind
从字符串pos位置开始往前找字符c,返回该字符在字符串中的位置
substr
在str中从pos位置开始, 截取n个字符,然后将其返回.
-
void main()
{
string str;
str.push_back('a');//插字符
str.append("a");//插字符串
str += 'b';
str += "b";
cout << str << endl;
cout << str.c_str() << endl; // 以C语言的方式打印字符串
string email("1030269471@qq.com");
size_t pos = email.find('@');//查找字符的位置,有重复查找第一次出现的位置.
if (pos != string::npos)
{
cout << "pos = " << pos << endl;
}
else
cout << "not find" << endl;
//截取
string email_type;
size_t strat_pos = email.find('@');
size_t end_pos = email.rfind('.');
email_type = email.substr(strat_pos+1, end_pos-strat_pos-1);
cout << email_type << endl;
}
注意:
- 在string尾部追加字符时,s.push_back© / s.append(1, c) / s += 'c’三种的实现方式差不一般
情况下string类的+=操作用的比较多,+=操作不仅可以连接单个字符,还可以连接字符串。
-
对string操作时,如果能够大概预估到放多少字符,可以先通过reserve把空间预留好.
-
string类非成员函数
operator+
尽量少用,因为传值返回,导致深拷贝效率低
operator>> (重点)
输入运算符重载
operator<< (重点)
输出运算符重载
getline (重点)
获取一行字符串
relational operators
大小比较
//void main() //{ // string s1; // getline(cin, s1);//获取字符函数 // cout << s1 << endl; //} //void main() //{ // string s1("hello"); // string s2("world"); // bool res = (s1 > s2);//根据返回值判断 //}
二.string类的模拟实现
1.浅拷贝和深拷贝
浅拷贝:也称值拷贝,编译器只是将对象中的值拷贝过来。如果对象中存在资源(堆上的内存),最后就会导致多个对象共享同一份资源,当一个对象销毁时就会将该资源释放吊,而此时另一些对象不知道该资源已经被释放,以为还有效,所以当继续堆资源操作时,就会发生非法访问。(改变了指针的指向).
深拷贝:如果一个类中涉及到资源的管理,我们必须给每个对象独立的分配资源,保证多个对象之间不会因为共享资源造成多次释放的程序崩溃问题。一个类中如果涉及到资源的管理,其拷贝构造函数,复制运算符重载以及析构函数必须要显式给出。一般情况都是按照深拷贝方式提供。
写时拷贝:
一、什么是写时拷贝?就是当你在读取一片空间时,系统并不会为你开辟一个一模一样的空间给你;只有在当你真正修改的时候,才会开辟一片空间给你。二、怎么实现写时拷贝呢?
(1)、使用引用计数来实现。所以我们在分配空间时需要多分配4个字节,来记录有多少个指针指向这个空间。
(2)、有新的指针指向这篇空间时,那么引用计数就加一;当有一个指针要释放该空间时,那么引用计数就减一。
(3)、当有指针要修改这片空间时,则为该指针重新分配自己的空间,原空间的引用计数减一,新空间的引用计数加一。
练习题
344. 反转字符串
class Solution { public: void reverseString(vector<char>& s) { size_t start = 0, end = s.size() - 1; while (start < end) swap(s[start++], s[end--]); } };
387. 字符串中的第一个唯一字符
class Solution { public: int firstUniqChar(string s) { int count[256]={0}; int size = s.size(); for(int i=0;i<size;++i) count[s[i]]+=1; for(int i=0;i<size;++i) if(1==count[s[i]]) return i; return -1; } };
拷贝构造模拟实现
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 main()
{
string s("hello bit");
string s1(s);
}