当前位置:首页 » 《随便一记》 » 正文

<C++_STL> string

4 人参与  2023年04月08日 17:45  分类 : 《随便一记》  评论

点击全文阅读


目录

1.string类

2.string类的接口

2.1 成员函数

2.1.1 string构造函数

2.1.2 string赋值运算

2.1.3 string析构函数

2.2 string对象访问以及迭代器

2.2.1 string的遍历方式

2.2.2 迭代器的使用

2.2.3 const_迭代器的使用

2.2.4 at

2.2.5 back和front

2.3 string容量操作

2.3.1 size/length/capacity/clear/empty/resize

2.3.2 reserve 

2.3.3 resize和reserve的区别 

 2.4 string修改操作

2.4.1 operator+=

2.4.2 push_back/pop_back

2.4.3 append

2.4.4 assign

2.4.5 insert / erase

2.4.6 replace

2.4.7 swap

2.5 string操作

2.5.1 c_str

2.5.2 data

2.5.3 copy 

2.5.4 find/rfind

2.5.5 find_first/last_of和find_first/last_not_of

2.5.6 substr

2.5.7 compare

2.6 非成员函数接口

2.6.1 getline

3.string模拟实现

3.1经典string类问题

3.2 浅拷贝和深拷贝

3.3 string模拟实现代码(常用接口)


C语言中,字符串是以'\0'结尾的一些字符的集合,为了操作方便,C标准库中提供了一些str系列的库函数, 但是这些库函数与字符串是分离开的,不太符合OOP的思想,而且底层空间需要用户自己管理,稍不留神可能还会越界访问

1.string类

1.string类是表示字符序列的类

2.标准的string类提供了对此类对象的支持,其接口类似于标准字符容器的接口,但添加了专门用于操作单字节字符字符串的设计特性。

3.string类是使用char(即作为它的字符类型,使用它的默认char_traits和分配器类型(关于模板的更多信息,请参阅basic_string)。

4.string类是basic_string模板类的一个实例,它使用char来实例化basic_string模板类,并用char_traits和allocator作为basic_string的默认参数(根于更多的模板信息请参basic_string)。

5.注意,这个类独立于所使用的编码来处理字节:如果用来处理多字节或变长字符(如UTF-8)的序列,这个类的所有成员(如长度或大小)以及它的迭代器,将仍然按照字节(而不是实际编码的字符)来操作。

总结:

1. string是表示字符串的字符串类

2. 该类的接口与常规容器的接口基本相同,再添加了一些专门用来操作string的常规操作。

3. string在底层实际是:basic_string模板类的别名,typedef basic_string string;

4. 不能操作多字节或者变长字符的序列。

在使用string类时,必须包含#include<string>头文件以及using namespace std

2.string类的接口

2.1 成员函数

2.1.1 string构造函数

函数名称功能说明
string()默认构造函数,创建一个空字符串。
string(const char* str)使用C风格的字符串s构造一个string对象。
string(const string& str)拷贝构造函数,用一个已有的string对象来构造新的对象。
string(size_t n, char c)用字符c重复n次构造新的字符串。
string(const char* str, size_t n)创建一个字符串对象,其内容是由 C 风格的字符串 str 的前 n 个字符给定的 
string(const string& str, size_t pos, size_t n = npos) 创建一个字符串对象,其内容是字符串对象 str 中从位置 pos 开始的 n 个字符 
template <class InputIterator> string(InputIterator begin, InputIterator end)创建一个字符串对象,其内容是由迭代器对 [begin, end) 中的字符序列给定的

 下面是这些接口的测试: 

#include <iostream>#include <string>using namespace std;int main(){    // 1.string()    string s1; // 构造空的string类对象s1    // 2.string(const char* str)    string s2("Hello World\n"); // 用C格式字符串构造string类对象s2    string s3 = "Hello World";    // 3.string(const string& str)    string s31(s3);      // 拷贝构造s3    cout << s31 << endl; // Hello World    // 4.string(size_t n, char c):用字符c重复n次构造新的字符串。    string s4(3, 'a');    cout << s4 << endl; // aaa    // 5.string(const char* str, size_t n) :创建一个字符串对象,其内容是由 C 风格的字符串 str 的前 n 个字符给定的     string s5("Hello World", 5); // 取字符串前5个    cout << s5 << endl;          // Hello    // 6.string(const string& str, size_t pos, size_t n = npos) :创建一个字符串对象,其内容是字符串对象str中从位置pos开始的 n 个字符     string s6(s3, 6, 3); // 从s3的第6个字符开始取后三个字符    cout << s6 << endl;  // Wor    string s7(s3, 6, 13); // 取13个字符,超过了,就有多少取多少    cout << s7 << endl;   // World    string s8(s3, 1);   // 取1后面的所有字符    cout << s8 << endl; // ello World    for (size_t i = 0; i < s2.size(); i++)    {        s2[i]++;    }    cout << s2 << endl; // Ifmmp!Xpsme */    // 7.template <class InputIterator> string(InputIterator begin, InputIterator end):创建一个字符串对象,其内容是由迭代器对 [begin, end) 中的字符序列给定的    char arr[] = {'H', 'e', 'l', 'l', 'o'};    string str(begin(arr), end(arr)); // Hello    cout << str << endl;    return 0;}

2.1.2 string赋值运算

函数名称功能说明
string& operator=(const string& str);将一个字符串对象 str 赋值给当前的字符串对象,返回当前字符串对象的引用。
string& operator=(const char* s)将一个 C 风格的字符串 s 赋值给当前的字符串对象,返回当前字符串对象的引用
string& operator=(char c)将一个字符 c 赋值给当前的字符串对象,返回当前字符串对象的引用。
#include <iostream>#include <string>using namespace std;int main(){    // 1.string& operator=(const string& str)    string str1 = "Hello";    string str2 = "World";    str1 = str2;          // 将 str2 的值赋给 str1    cout << str1 << endl; // 输出:World    // 2.string& operator=(const char* s)    string str3 = "Hello";    str3 = "World";       // 将 C 风格字符串 "World" 赋给 str    cout << str3 << endl; // 输出:World    // string& operator=(char c)    string str4 = "Hello";    str4 = 'W';           // 将字符 'W' 赋给 str    cout << str4 << endl; // 输出:W    return 0;}

2.1.3 string析构函数

string 类的析构函数会自动被编译器生成,无需手动实现。当一个 string 类型的对象生命周期结束时,其析构函数会被自动调用,用于释放对象占用的内存空间。

string 类的析构函数没有任何参数,也没有返回值。它会自动释放对象占用的内存,包括对象所持有的动态内存和任何由 string 对象分配的缓冲区。

例如,当一个 string 类型的对象超出作用域、被 delete 运算符释放或者存储它的容器被销毁时,其析构函数会被自动调用。

2.2 string对象访问以及迭代器

2.2.1 string的遍历方式

函数名称功能说明

char& operator[](size_t pos)

const char& operator[](size_t pos) const

返回pos位置的字符,const string类对象调用

iterator begin()

const_iterator begin() const

iterator end()

const_iterator end() const

begin获取一个字符的迭代器 + end获取最后一个字符下一个位置的迭代器

iterator rbegin()

const_iterator rbegin() const

iterator rend()

const_iterator rend() const

begin获取一个字符的迭代器 + end获取最后一个字符下一个位置的迭代器
范围forC++11支持更简洁的范围for的新遍历方式
// string的遍历// begin()+end()   for+[]  范围for// 注意:string遍历时使用最多的还是for+下标 或者 范围for(C++11后才支持)// begin()+end()大多数使用在需要使用STL提供的算法操作string时,比如:采用reverse逆置stringvoid Teststring3(){    string s1("hello World");    const string s2("hello World2");    cout << s1 << " " << s2 << endl;       // hello World hello World2    cout << s1[0] << " " << s2[0] << endl; // h H    s1[0] = 'H';    cout << s1 << endl; // Hello World    // 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] << " ";    cout << endl;    // 2.迭代器    string::iterator it = s.begin();    while (it != s.end())    {        cout << *it << " ";        ++it;    }    cout << endl;    // string::reverse_iterator rit = s.rbegin();    // C++11之后,直接使用auto定义迭代器,让编译器推到迭代器的类型    auto rit = s.rbegin();    while (rit != s.rend())    {        cout << *rit << " ";        rit++;    }    cout << endl;    // 3.范围for    for (auto ch : s)        cout << ch << " ";    cout << endl;}

2.2.2 迭代器的使用

int main(){    string s1("Hello World");    // 遍历和读写容器的数据    string::iterator it = s1.begin();  //H e l l o   W o r l d    while (it != s1.end())    {        cout << *it << " ";        it++;    }    cout << endl;    // 反向迭代器    string s2("Hello World");    string::reverse_iterator rit = s2.rbegin();    while (rit != s2.rend())    {        cout << *rit << " ";  //d l r o W   o l l e H        rit++;    }    cout << endl;    return 0;}

2.2.3 const_迭代器的使用

int main(){    const string s("Hello World");    // 遍历和读容器的数据,不能写    // string::iterator it = s.begin();  //err s为const,迭代器也应该是const    string::const_iterator it = s.begin();    while (it != s.end())    {        //*it+=1;//err,const不能改变数据        cout << *it << " ";   // H e l l o   W o r l d        it++;    }    cout << endl;    // 反向const迭代器,    string::const_reverse_iterator rit = s.rbegin();    // auto rit = s.rbegin();  //用auto类型代替string::const_reverse_iterator,auto编译器自动识别类型    while (rit != s.rend())    {        cout << *rit << " ";   //d l r o W   o l l e H        ++rit;  //反向迭代器这里也是++,而不是--    }    cout << endl;    return 0;}

2.2.4 at

在访问字符串时,如果指定的索引超出了字符串的范围,就会抛出异常

char& at(size_t pos); 返回一个引用,可以用于读取或修改字符串中指定位置的字符。
const char& at(size_t pos) const;返回的是一个 const 引用,因此只能用于读取字符串中指定位置的字符,不能修改它。
#include <iostream>#include <string>using namespace std;int main(){    string str = "Hello World";    char first_char = str.at(0);    char last_char = str.at(str.length() - 1);    cout << "First character:" << first_char << endl; // First character:H    cout << "Last character:" << last_char << endl;   // Last character:d    string str1 = "Hello World";    const char &ch = str.at(0);    // ch = 'E';  //编译错误:尝试修改常量引用    const string str2 = "Hello World";    // str.at(0) = 'E';  //编译错误:尝试修改常量字符串        //string s1("Hello World");    //s1[100];    // 出错assert    s1.at(100);   // 超过索引范围,抛异常    return 0;}

2.2.5 back和front

char& back();

const char& back() const;

front函数返回一个对字符串第一个字符的引用,如果字符串为空,会导致未定义行为。

char& front();

const char& front() const;

back函数返回一个对字符串最后一个字符的引用,如果字符串为空,也会导致未定义行为。
#include <iostream>#include <string>using namespace std;int main(){    string str = "Hello World";    char c1 = str.front();    char c2 = str.back();    cout << c1 << endl;   //H    cout << c2 << endl;   //d    return 0;}

2.3 string容量操作

函数名称功能说明
size_t size() const返回字符串有效字符长度
size_t length() const返回字符串有效字符长度
size_t max_size() const返回字符串最大可能的大小,即 std::allocator_traits<allocator_type>::max_size() 的返回值。

void resize(size_t n)

void resize(size_t n, char c)

将有效字符的个数该成n个,多出的空间用字符c填充
size_t capacity() const 返回空间总大小
void reserve(size_t n = 0)为字符串预留空间
void clear()清空有效字符
bool empty() const 检测字符串释放为空串,是返回true,否则返回false
void shrink_to_fit()

请求字符串减小为其当前大小,可能会导致内存重新分配  

2.3.1 size/length/capacity/clear/empty/resize

// size/length/capacity/clear/resize/emptyvoid Teststring(){    // 注意:string类对象支持直接用cin和cout进行输入和输出    string s("Hello,World!");    cout << s.size() << endl;     // 12    cout << s.length() << endl;   // 12    cout << s.capacity() << endl; // 15  显示15,其实容量是16,少一个\0    cout << s << endl;    // 将s中的字符串清空,注意清空时只是将size清0,不改变底层空间的大小    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中有效字符个数增加到15个,多出位置用缺省值'\0'进行填充    // "aaaaaaaaaa\0\0\0\0\0"    // 注意此时s中有效字符个数已经增加到15个    s.resize(15);    cout << s.size() << endl;     // 15    cout << s.capacity() << endl; // 15    cout << s << endl;            // aaaaaaaaaa    // 将s中有效字符个数缩小到5个    s.resize(5);    cout << s.size() << endl;     // 5    cout << s.capacity() << endl; // 15  size缩小,不会改变capacity    cout << s << endl;            // aaaaa    cout << s.max_size() << endl; // 9223372036854775807    cout << s.empty() << endl;    // 0    s.clear();    cout << s.empty() << endl; // 1}int main(){    Teststring();    return 0;}

2.3.2 reserve 

测试reserve是否会改变string中有效元素个数

void Teststring(){        string s;    // 测试reserve是否会改变string中有效元素个数    s.reserve(100);    cout << s.size() << endl;  //0    cout << s.capacity() << endl;  //100    // 测试reserve参数小于string的底层空间大小时,是否会将空间缩小    s.reserve(50);    cout << s.size() << endl;  //0    cout << s.capacity() << endl;  //50    // reserve无法缩容到    s="Hello World";    s.reserve(1);    cout<<s.size()<<endl;   //11    cout<<s.capacity()<<endl;  //15    s.reserve(17);    cout<<s.capacity()<<endl;  //30  reserve默认扩容2倍,不同编译器下结果不同    s.reserve(1);    cout<<s.capacity()<<endl;  //15  reserve缩容不会缩小到字符串有效长度的空间还小,只能缩容之前reserve过的空闲空间}

reserve不会改变string有效元素个数

reserve参数小于string空间时,会使空间变小,但不会小于有效元素个数大小 

reserve默认扩容2倍,不同编译器下结果不同

利用reserve提高插入数据的效率,避免增容的开销

 测试代码:利用reserve提高插入数据的效率,避免增容带来的开销

// 利用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';        }    }}

2.3.3 resize和reserve的区别 

int main(){    string s1("Hello World");    // 扩容    s1.reserve(100);    cout << s1.size() << endl;     // 11    cout << s1.capacity() << endl; // 100    string s2("Hello World");    // 扩容+初始化    s2.resize(100);                // 默认填充0    cout << s2.size() << endl;     // 100    s2.resize(100, 'x');           // 填充x    cout << s2.size() << endl;     // 100    cout << s2.capacity() << endl; // 100    // 比size小,就不是扩容,就是删除,size会变,但capacity不变    // 缩容不支持原地缩容    s2.resize(5);    cout << s2.size() << endl;  //5    cout << s2.capacity() << endl;  //100    return 0;}

string的resize会改变其大小并且可能会改变其内容,而reserve仅仅是为string预留一定的内存空间,不改变其大小和内容。

注意:

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的底层空间总大小时,reserver不会改变容量大小。

 2.4 string修改操作

2.4.1 operator+=

int main(){    string str = "Hello";    char c = ' ';       //string& operator+=(char c);    str += c;    //string& operator+=(const char* s);    str += 'w';    //string& operator++(const string& str);    str += "orld";    cout << str << endl;    return 0;}

2.4.2 push_back/pop_back

int main(){    string str = "Hello";    str.push_back('a');    cout << str << endl;  //Helloa    str.pop_back();    cout << str << endl;  //Hello    return 0; }

2.4.3 append

#include <iostream>#include <string>#include <vector>using namespace std;int main(){    // 1.string& append(const string& str)    string str = "hello";    string appendstr = " world!";    str.append(appendstr);    cout << str << endl; // hello world!    // 2.string& append(const string& str, size_t subpos, size_t sublen)    // 将给定字符串str的子串(从索引subpos开始,长度为sublen)添加到当前字符串的末尾。    string str1 = "hello";    string appendStr1 = " world!";    str1.append(appendStr1, 0, 5); // 添加另一个字符串的子串,即" worl"    cout << str1 << endl;          // 输出:hello worl    // 3.string& append(const char* s)    string str2 = "hello";    const char *cstr = " world!";    str2.append(cstr);    // 添加完整的字符数组,即" world!"    cout << str2 << endl; // 输出:hello world!    // 4.string& append(const char* s, size_t n)    // 将给定的字符数组s的前n个字符添加到当前字符串的末尾。    string str3 = "hello";    const char *cstr3 = " world!";    str3.append(cstr3, 7); // 添加" world!"的前7个字符,即" world"    cout << str3 << endl;  // 输出:hello world    // 5. string& append(size_t n, char c)    // 将字符c重复n次添加到当前字符串的末尾。    string str4 = "hello";    str4.append(3, '!');  // 添加3个感叹号    cout << str4 << endl; // 输出:hello!!!    // 6.    // template<class InputIterator>    // void append(InputIterator first, InputIterator last);    // 作用是将从first到last区间中的所有元素添加到当前std::string对象的末尾。    vector<char> vec{'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!'};    string str5;    str5.append(vec.begin(), vec.end());    cout << str5 << endl; // hello,world!    return 0;}

2.4.4 assign

可以用于将一个字符串替换成新的字符串

#include <iostream>#include <string>#include <vector>using namespace std;int main(){    // 1.string& assign(const string& str)    string s1 = "Hello";    string s2;    s2.assign(s1);    cout << s2 << endl; // Hello    // 2.string& assign(const std::string& str, size_t subpos, size_t sublen)    // 将字符串对象设置为另一个字符串对象str的子串,子串从subpos开始,长度为sublen。    string s3 = "Hello World!";    string s4;    s4.assign(s3, 6, 5); //    cout << s4 << endl;  // World    // 3.string& assign(const char*s)    string s5;    const char *cstr = "Hello World!";    s5.assign(cstr);    //    cout << s5 << endl; // Hello World!    // 4.string& assign(const char* s, size_t n)    string s6;    const char *cstr1 = "Hello World!";    s6.assign(cstr1, 5);    cout << s6 << endl; // Hello    // 5.string& assign(size_t n, char c)    string s7;    s7.assign(5, 'a');    cout << s7 << endl; // aaaaa    // 6.template <class InputIterator>    // string &assign(InputIterator first, InputIterator last);    // 将字符串对象设置为迭代器[first, last)所指范围内的字符序列的副本。    string s8;    vector<char> vec = {'H', 'e', 'l', 'l', 'o'};    s8.assign(vec.begin(), vec.end());    cout << s8 << endl; // Hello    return 0;}

2.4.5 insert / erase

int main(){    string s1("World");    s1.insert(0, "hello");    cout << s1 << endl;  //    // s1.insert(5, " "); //在s1第五个位置插入空格    // s1.insert(5,' ');  //err    // s1.insert(5, 1, ' '); // 在s1第五个位置插入1个字符    s1.insert(s1.begin() + 5, ' ');    cout << s1 << endl;    // insert/erase不推荐经常使用,能少用就少用    // 因为他们可能都存在挪动数据效率低下    string s2("Hello World");    // s2.erase(5, 1);  //删除第五个位置1个字符    s2.erase(s2.begin() + 5); // 删除第五个位置后面的字符    cout << s2 << endl;    s2.erase(5, 30); // 超过字符串长度,删除所有的    s2.erase(5);     // 删除所有的用这种方式    cout << s2 << endl;    return 0;}

2.4.6 replace

替换字符串

int main(){    string s1("Hello World");    s1.replace(5, 1, "%%d");    cout << s1 << endl;  //Hello%%dWorld    string s2("Hello World i love you");    size_t num = 0;    for (auto ch : s2)    {        if (ch == ' ')            num++;    }    // 提前开空间,避免replace时扩容    s2.reserve(s2.size() + 2 * num);    size_t pos = s2.find(' ');    while (pos != string::npos)    {        s2.replace(pos, 1, "%20");        pos = s2.find(' ', pos + 3); // pos+3的位置是越过了%20    }    cout << s2 << endl;  //Hello%20World%20i%20love%20you    return 0;}

2.4.7 swap

为什么C++库里面已经有swap函数了,为什么string里还有swap

库里的库函数深拷贝,效率低

int main(){    string newStr = "Hello,World";    string s1 = newStr;    cout << newStr << endl; // Hello,World    string s2("xxxxx");    s1.swap(s2);    cout << s1 << endl; // xxxxx    cout << s2 << endl; // Hello,World    swap(s1, s2);    cout << s1 << endl; // Hello,World    cout << s2 << endl; // xxxxx    return 0;}

2.5 string操作

2.5.1 c_str

返回C格式字符串

int main(){    string s1("Hello World");    cout << s1 << endl;    // c_str 是指针    cout << s1.c_str() << endl;    cout << (void *)s1.c_str() << endl;    s1 += '\0';    s1 += '\0';    s1 += "xxxxx";    cout << s1 << endl;         // Hello Worldxxxxx    cout << s1.c_str() << endl; // Hello World    C语言方式打印,遇到\0结束    // c_str 用于C语言方式字符串    string filename("test.cpp");    FILE *fout = fopen(filename.c_str(), "read");    char ch = fgetc(fout);    while (ch != EOF)    {        cout << ch;        ch = fgetc(fout);    }    fclose(fout);    return 0;}

2.5.2 data

返回指向string对象中存储的字符数组的指针,即返回一个C风格的字符串指针。

int main(){    string str = "Hello, world!";    const char *cstr = str.data();    cout << "The string is: " << str << endl;  //The string is: Hello, world    cout << "The C-style string is: " << cstr << endl;  //The C-style string is: Hello, world!    // 修改字符串    string new_str(cstr);    new_str[0] = 'h';    cout << "The modified C-style string is: " << new_str.c_str() << endl; //The modified C-style string is: hello, world!    cout << "The modified string is: " << new_str << endl; //The modified string is: hello, world!    return 0;}

2.5.3 copy 

int main(){    // size_t copy (char* s, size_t len, size_t pos = 0) const;    // 其中,c是一个指向目标字符数组的指针,len是要复制的字符数,pos是开始复制的位置,默认值为 0。    string str = "Hello World!";    char buf[6];    size_t n = str.copy(buf, 5, 6);    buf[n] = '\0';    cout << buf << endl; // World    return 0;}

2.5.4 find/rfind

find 函数返回子字符串第一次出现的位置,如果子字符串未找到,则返回 npos

rfind 方法返回子字符串最后一次出现的位置,如果子字符串未找到,则返回npos

npos是string里面的一个静态成员变量

static const size_t npos = -1;

int main(){    string str1 = "Hello World,Hello World";    string str2 = "Wor";    cout << str1.find(str2) << endl;   // 6    cout << str1.rfind(str2) << endl;  // 18    cout << str1.find("Wor") << endl;  // 6    cout << str1.rfind("Wor") << endl; // 18    const char *substr = "Wor";    cout << str1.find(substr) << endl;  // 6    cout << str1.rfind(substr) << endl; // 18    cout << str1.find('d') << endl;     // 10    cout << str1.rfind('d') << endl;    // 22    return 0;}

2.5.5 find_first/last_of和find_first/last_not_of

 用于在字符串中查找第一次/最后一次出现指定字符集合中任何一个字符的位置。

 用于再字符串中查找第一次/最后一次不是出现指定字符集合中任何一个字符的位置

int main(){    string str = "Hello World,Hello World";    cout << str.find_first_of("aeiou") << endl; // 查找"aeiou"第一次出现的位置,Hello World e为1    cout << str.find_last_of("aeiou") << endl;  // 最后出现"aeiou"的位置是19    cout << str.find_first_not_of("aeiou") << endl; // 查找第一次不是"aeiou"出现的位置   为0  H一开始就不是    cout << str.find_last_not_of("aeiou") << endl;  // 查找最后一次不是的位置 22  为d    return 0;}

2.5.6 substr

 用于返回字符串中指定位置和长度的子字符串。

int main(){    string str = "Hello, world!";    string substr1 = str.substr(7, 5); // 从位置7开始提取长度为5的子字符串,得到"world"    string substr2 = str.substr(0, 5); // 从位置0开始提取长度为5的子字符串,得到"Hello"    string substr3 = str.substr(7);    // 从位置7开始提取到字符串末尾的子字符串,得到"world!"    cout << substr1 << endl; // 输出"world"    cout << substr2 << endl; // 输出"Hello"    cout << substr3 << endl; // 输出"world!"    return 0;}

2.5.7 compare

用于比较两个字符串的成员函数,它返回一个整数值,表示两个字符串的大小关系

如果当前字符串对象小于 str,则返回一个负数(通常是 -1)。如果当前字符串对象等于 str,则返回 0。如果当前字符串对象大于 str,则返回一个正数(通常是 1)。
int main() {    string str1 = "apple";    string str2 = "banana";    string str3 = "apple";        int result1 = str1.compare(str2);    int result2 = str1.compare(str3);        cout << "str1 vs str2: " << result1 << endl; // 输出-1    cout << "str1 vs str3: " << result2 << endl; // 输出0        return 0;}

2.6 非成员函数接口

2.6.1 getline

istream& getline (istream& is, string& str, char delim);

此函数将输入流对象 is 中的文本读取到 str 字符串中,直到遇到分隔符 delim 或文件结尾。如果 delim 参数被省略,则默认使用换行符 \n 作为分隔符。

int main(){    string name;    cout << "Please enter your name: ";    getline(cin, name);    cout << "Hello, " << name << "!" << endl;    return 0;}

3.string模拟实现

3.1经典string类问题

上面已经对string类进行了简单的介绍,大家只要能够正常使用即可。在面试中,面试官总喜欢让学生自己 来模拟实现string类,最主要是实现string类的构造、拷贝构造、赋值运算符重载以及析构函数。大家看下以 下string类的实现是否有问题?

// 为了和标准库区分,此处使用Stringclass 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共用同一块内存空间,在释放时同一块 空间被释放多次而引起程序崩溃,这种拷贝方式,称为浅拷贝。

3.2 浅拷贝和深拷贝

浅拷贝:也称位拷贝,编译器只是将对象中的值拷贝过来。如果对象中管理资源,最后就会导致多个对象共 享同一份资源,当一个对象销毁时就会将该资源释放掉,而此时另一些对象不知道该资源已经被释放,以为 还有效,所以当继续对资源进项操作时,就会发生发生了访问违规。

就像一个家庭中有两个孩子,但父母只买了一份玩具,两个孩子愿意一块玩,则万事大吉,万一不想分享就 你争我夺,玩具损坏。

可以采用深拷贝解决浅拷贝问题,即:每个对象都有一份独立的资源,不要和其他对象共享。父母给每个孩 子都买一份玩具,各自玩各自的就不会有问题了。

如果一个类中涉及到资源的管理,其拷贝构造函数、赋值运算符重载以及析构函数必须要显式给出。一般情况都是按照深拷贝方式提供。

3.3 string模拟实现代码(常用接口)

#pragma once#include <iostream>#include <string.h>#include <assert.h>using namespace std;namespace phw{class string{private:friend ostream &operator<<(ostream &out, const phw::string &s);friend istream &operator>>(istream &in, phw::string &s);public:// 带参构造函数// string(const char* str = nullptr)  //不可以 给空指针,strlen会报错// string(const char* str = '\0')  //\0 char转换成指针,也是空指针// string(const char* str = "\0")   //可以,给常量字符串,strlen不会报错string(const char *str = "") // 空字符串默认是\0: _size(strlen(str)){_capacity = _size == 0 ? 3 : _size; // 最少给3个字节空间_str = new char[_capacity + 1];// new _capacity+1  capacity是字符串容量,存放的有效字符大小,不是空间,空间还有一个\0strcpy(_str, str);}// 拷贝构造string(const string &s): _size(s._size),  _capacity(s._capacity){//_str自己开空间_str = new char[s._capacity + 1];strcpy(_str, s._str);}// 赋值是对已经定义的对象进行赋值// 有一种情况是,原对象的空间远大于要赋值的对象,那么就会出现空间浪费// 所以首先应该delete掉原空间的内存,在进行赋值string &operator=(const string &s){if (this != &s){// delete[]_str;  //赋值提前把旧空间释放,防止浪费空间//_str = new char[s._capacity + 1];// strcpy(_str, s._str);//_size = s._size;//_capacity = s._capacity;// 下面的写法更加安全char *tmp = new char[s._capacity + 1];strcpy(tmp, s._str);delete[] _str;_str = tmp;_size = s._size;_capacity = s._capacity;}return *this;}// 迭代器相关typedef char *iterator;typedef const char *const_iterator;iterator begin(){return _str;}const_iterator begin() const{return _str;}iterator end(){return _str + _size;}const_iterator end() const{return _str + _size;}// 获取字符串const char *c_str(){return _str;}//[]通过下标来访问字符char &operator[](size_t pos){return _str[pos];}// 访问const类型的数组const char &operator[](size_t pos) const{return _str[pos];}size_t size() const{return _size;}size_t capacity() const{return _capacity;}~string(){delete[] _str;_size = 0;_capacity = 0;}void Print(const string &s){for (size_t i = 0; i < s.size(); i++){cout << s._str[i] << " ";}cout << endl;// 这里不支持范围for了,为什么?  因为这里s是const对象,只能调用const迭代器string::const_iterator it = s.begin();while (it != s.end()){//(*it)++;  //err. const迭代器指向的内容不能修改it++;}// 这里没有定义const迭代器,就会报错,范围for的底层就是迭代器for (auto ch : s){cout << ch << " ";}cout << endl;}// 不修改成员变量数据的函数,最好加上constbool operator==(const string &s) const{return strcmp(_str, s._str) == 0;}bool operator!=(const string &s) const{return !(_str == s._str);}bool operator>(const string &s) const{return strcmp(_str, s._str) > 0;}bool operator>=(const string &s) const{return *this > s || *this == s;}bool operator<(const string &s) const{return !(*this >= s);}bool operator<=(const string &s) const{return !(*this > s);}// 开空间void reserve(size_t n){if (n > _capacity){char *tmp = new char[n + 1];strcpy(tmp, _str);delete[] _str;_str = tmp;_capacity = n;}}// 扩容+初始化void resize(size_t n, char ch = '\0'){// 当n小于_size的时候,不需要扩容,也不需要缩容// n大于_size的时候,并且当n>capacit的时候需要扩容,就直接调用reserveif (n < _size){// 保留前n个_size = n;_str[_size] = '\0';}else{if (n > _capacity){reserve(n);}// 不大于则不需要设置_capacity// 从_size开始 到需要扩容n开始,初始化\0size_t i = _size;while (i < n){_str[i] = ch;i++;}_size = n;// 将最后的下一个位置也设置为\0_str[_size] = '\0';}}void push_back(char ch){if (_size + 1 > _capacity){reserve(_capacity * 2);}_str[_size] = ch;_size++;_str[_size] = '\0';}// 尾插字符串void append(const char *str){size_t len = strlen(str);if (_size + len > _capacity){reserve(_size + len);}strcpy(_str + _size, str); // 从_str+_size开始拷贝// strcat(_str, str);     //strcat会找\0,效率低下_size += len;_str[_size] = '\0';}string &operator+=(const char *str){append(str);return *this;}string &operator+=(const char ch){push_back(ch);return *this;}string &insert(size_t pos, char ch){assert(pos <= _size);if (_size + 1 > _capacity){reserve(_capacity * 2);}int end = _size;// 这里的pos需要改成int pos是无符号类型,和end对比,end会转换成无符号类型// 当pos的位置是0时,end为无符号类型将永远不会小于0,程序无限循环。// 需要将pos转换成int,那么end就为int类型while (end >= (int)pos){_str[end + 1] = _str[end];end--;}_str[pos] = ch;_size++;return *this;}string &insert(size_t pos, const char *str){assert(pos <= _size);int len = strlen(str);int end = _size + len;if (_size + len > _capacity){reserve(_size + len);}while (end > pos + len - 1){_str[end] = _str[end - len];end--;}strncpy(_str + pos, str, len);_size += len;return *this;}string &erase(size_t pos, size_t len = npos){// 如果要删的个数远超于剩余的个数,就是pos位置后面全部删除,直接在pos位置后面置\0即可//  len == npos必须加上,npos是最大值if (len == npos || pos + len >= _size){_str[pos] = '\0';_size = pos;}else{strcpy(_str + pos, _str + pos + len); // 删除pos+len位置的字符串_size -= len;}return *this;}void swap(string &s){std::swap(_str, s._str);std::swap(_size, s._size);std::swap(_capacity, s._capacity);}size_t find(char ch, size_t pos = 0){assert(pos < _size);for (size_t i = 0; i < _size; i++){if (_str[i] == ch){return i;}}}// 返回子串str在string中第一次出现的位置size_t find(const char *str, size_t pos = 0){assert(pos < _size);// p是str出现在_str+pos出现的位置,返回的是指针char *p = strstr(_str + pos, str);if (p == nullptr){return npos;}else{return p - _str;}}void clear(){_str[0] = '\0';_size = 0;}private:char *_str;size_t _size;size_t _capacity; // 真实容量要比_size多1,多一个\0// 静态成员变量不能给缺省值,但是加上const就可以了,只针对整型static const size_t npos = -1;// static const size_t N = 10;// int _a[N];};ostream &operator<<(ostream &out, const phw::string &s){for (size_t i = 0; i < s.size(); i++){out << s[i];}return out;}istream &operator>>(istream &in, phw::string &s){s.clear(); // 一开始就清理缓冲区char ch = in.get();char buff[128];size_t i = 0;while (ch != ' ' && ch != '\n'){// s += ch;  //字符串太长可能会容量不够,用reserve如何控制扩容? 扩容会频繁调用buff[i++] = ch;if (i == 127){buff[127] = '\0';s += buff;i = 0;}ch = in.get();}if (i != 0){buff[i] = '\0';s += buff;}// getline实现/*while (ch != '\n'){s += ch;ch = in.get();}*/return in;}}
#include "string.h"void test1(){phw::string s1;phw::string s2("Hello World\n");cout << s1.c_str() << endl;cout << s2.c_str() << endl; // Hello World}void test2(){phw::string s1;phw::string s2("hello world");phw::string s3(s2);// 编译器默认的构造函数,浅拷贝,s2和s3的str指向了同一个空间,析构会出问题cout << s2.c_str() << endl; // hello worldcout << s3.c_str() << endl; // hello world// 不自己写拷贝构造结果是s2变,s3跟着变,因为s2和s3指向同一个空间// s2[0]++;// cout << s2.c_str() << endl;   //iello world// cout << s3.c_str() << endl;   //iello worlds2[0]++;cout << s2.c_str() << endl; // iello worldcout << s3.c_str() << endl; // hello worlds1 = s3;// 自己不写还是会报错,因为还是浅拷贝cout << s1.c_str() << endl; // hello worldcout << s3.c_str() << endl; // hello worlds1 = s1;}void test3(){phw::string s1("Hello World");for (size_t i = 0; i < s1.size(); i++){s1[i]++;}for (size_t i = 0; i < s1.size(); i++){cout << s1[i] << " "; // I f m m p ! X p s m e}cout << endl;s1.Print(s1); // I f m m p ! X p s m ephw::string::iterator it = s1.begin();while (it != s1.end()){(*it)--;it++;}it = s1.begin();while (it != s1.end()){cout << *it << " "; // H e l l o   W o r l dit++;}cout << endl;for (auto ch : s1) // 底层就是将*it替换成ch{cout << ch << " "; // H e l l o   W o r l d}cout << endl;}// string比较大小void test4(){phw::string s1("hello world");phw::string s2("hello world");phw::string s3("xx");cout << (s1 < s2) << endl;// 0cout << (s1 == s2) << endl; // 1cout << (s1 > s2) << endl;// 0}void test5(){phw::string s1("Hello World");s1.push_back('a');s1.append("xxxxxxxxxx");s1 += 'W';s1 += "!!!!!!!!!!!!";cout << s1.c_str() << endl; // Hello WorldaxxxxxxxxxxW!!!!!!!!!!!!phw::string s2 = "Hello World";s2.insert(5, 'X');cout << s2.c_str() << endl; // HelloX Worlds2.insert(0, 'A');cout << s2.c_str() << endl; // AHelloX Worlds2.insert(0, "PHW");cout << s2.c_str() << endl; // PHWAHelloX Worlds2.erase(0, 3);cout << s2.c_str() << endl; // AHelloX Worlds2.erase(5, 10);cout << s2.c_str() << endl; // AHell}// 流插入重载必须实现成友元函数?  不对void test6(){std::string s1("0123456789");phw::string s2("0123456789");s1 += '\0';s2 += '\0';s1 += "xxxx";s2 += "xxxx";cout << s1 << endl;// 0123456789xxxxcout << s2.c_str() << endl; // 0123456789  遇到\0终止cout << s2 << endl;// 0123456789xxxxphw::string s3;cin >> s3;cout << s3 << endl;}void test7(){phw::string s1;std::string s2;cout << sizeof(s1) << endl; // 12cout << sizeof(s2) << endl; // 28s1 = "hello";s2 = "hello";cout << sizeof(s1) << endl; // 12cout << sizeof(s2) << endl; // 28// g++ 中x86  4字节   x64  8字节// g++中存的是指针}void test8(){string s1 = "Hello World";int pos = s1.find("Wor", 3);s1[pos] = 'A'; // Hello Aorldcout << s1;}int main(){// test8();return 0;}


点击全文阅读


本文链接:http://zhangshiyu.com/post/58913.html

<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1