[STL]string的使用+模拟实现
文章目录
- [STL]string的使用+模拟实现
- 一、STL
- 1.什么是STL
- 2.如何学习STL
 
- 二、string
- 1.string类的介绍
- 2.string的常用接口
- string的构造
- string的迭代器
- string的容量操作
- string的访问
- string的修改
- string的其他接口
- string的非成员函数接口
 
 
- 三、string的模拟实现
- string.h
- test.cpp
 
 
 
一、STL
1.什么是STL
1.STL (standard template libaray - 标准模板库):是C++标准库的重要组成部分,不仅是一个可复用的组件库,而且是一个包罗数据结构与算法的软件框架。

它包含了vector /stack/queue/priority_queue/list/set/map等。

我们在使用C++时不必再需要用轮子时,现场手搓出一个轮子了。
2.如何学习STL
1.我们进入CPP,即可开始学习。
我个人认为这个网站做的比C++的官网更好,使用更加方便。(一般使用旧版更好,新版不登录不能进行搜索)
2.我们也可以看书进行学习,例如《STL源码剖析》或者《C++ primer》。
二、string
1.string类的介绍
-  C语言中,字符串是以’\0’结尾的一些字符的集合,为了操作方便,C标准库中提供了一些str系列的库函数,但是这些库函数与字符串是分离开的,不太符合OOP的思想,而且底层空间需要用户自己管理,稍不留神可能还会越界访问。 
-  所以C++提供了一个string类,通过实现string的各种函数接口(插入、删除、清空等等),来帮助我们更方便的对字符进行操作。 
-  且在OJ中,有关字符串的题目基本以string类的形式出现,而且在常规工作中,为了简单、方便、快捷,基本都使用string类,很少有人去使用C库中的字符串操作函数。 
string并不属于STL,string比STL的诞生还要早。
2.string的常用接口
string的构造

- 还有一个拷贝构造函数
string(const string& s)

string的迭代器
Iterator是C++中定义的迭代器,我们在这里(string)简单先理解为指针。
typedef char* iterator;

- begin() : 返回第一个字符位置的迭代器
- end() : 返回最后一个字符的下一个位置(‘\0’)的迭代器
反向迭代器
- rbegin() : 返回指向最后一个字符的下一个位置(‘\0’)的迭代器
- rend() : 返回指向第一字符位置的迭代器
const 迭代器(为了满足const对象的调用)
-  cbegin() : 返回第一个字符位置的迭代器 
-  cend() : 返回最后一个字符的下一个位置(‘\0’)的迭代器 

string的容量操作

- size : 返回字符串长度
- capacity : 返回字符串容量
- empty : 返回字符串是否为空
- resize : 调整字符串大小,但分为3种情况

1.n < str.size(),把原来的size大小改为n
2.str.size() < n < str.capacity(), 修改字符串的size为n, 若有字符c的输入,将大于size小于capacity的部分设置为字符c
3.n > str.capacity(), 将原数组扩容到n, 若有字符c输入,则将size后面的部分全部设置为字符c

- reserve : 改变字符串容量
n > str.capacity(), 将字符串的capacity扩容到n
n <= str.capcaity(), 按编译器规则进行修改容量。(vs2019不进行修改)
reserve只会改变字符串容量,不会改变字符串的size大小。

- clear : 清空字符串

string的访问

operator[](最常用)
对[]进行运算符重载,实现对string对象的随机访问。

string的修改

- push_back : 尾插一个字符
- pop_back : 尾删一个字符
- operator+= : 运算符+=重载
相比于push_back,在string中我们更喜欢使用+=进行插入字符。
它可以插入插入一个字符或者插入一个字符串或者插入一个字符数组
 
 
- append : 类似于+=, 在字符串尾部追加数据

常用的有:
1.直接追加字符串
2.追加字符串的第几位到第几位
3.追加几个字符c

- insert : 插入数据

常用的:
1.在某个位置插入字符串
2.在某个位置插入几个字符c
3.在某个位置插入数组

- erase : 删除数据

常用:从pos位置删除到某个位置。

ps: 若只传起始位置pos,则缺省值npos为-1(npos为无符号数,则他是整形的最大值,erase会一直删除直到遇到’\0’)。
- swap
交换两个字符串的内容。(包括字符数组、有效数据个数,及容量大小)
 
 
string的其他接口
- c_str : 返回C形式的字符串
- find : 返回字符或者字符串在string对象中首次出现的位置
- rfind : 返回字符或者字符串在string对象中首次出现的位置(从最后一个字符开始找)
- substr : 将从pos位置到len个长度构建一个新string对象并返回

string的非成员函数接口
- operator>>

- operator<<

- getline : 插入含有空格的字符
我们在插入时,遇到一个空格、换行、或者回车,cin就会停止读取。
我们在插入必须含有空格的字符时,我们应该使用getline(cin, str)
而且我们还可以设置终止字符。
 

三、string的模拟实现
string.h
#pragma once
#include <iostream>
#include <string.h>
#include <assert.h>
using namespace std;
namespace myString
{
    class string
    {
        friend ostream& operator<<(ostream& out, const myString::string& s)
        {
            for (size_t i = 0; i < s.size(); i++)
            {
                out << s[i];
            }
            return out;
        }
        friend istream& operator>>(istream& in, myString::string& s)
        {
            s.clear();
            char buff[128] = { '\0' };
            size_t i = 0;
            char ch = in.get();
            while (ch != ' ' && ch !='\n')
            {
                if (i == 127)
                {
                    s += buff;
                    i = 0;
                }
                buff[i++] = ch;
                ch = in.get();
            }
            if (i > 0)
            {
                buff[i] = '\0';
                s += buff;
            }
            return in;
        }
    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);
            swap(tmp);
        }
        /*string& operator=(const string& s)
        {
            if (this != &s)
            {
                char* tmp = new char[s._capacity + 1];
                strcpy(tmp, s._str);
                delete[] _str;
                _str = tmp;
                _size = s._size;
                _capacity = s._capacity;
            }
            return *this;
        }*/
        string& operator=(string s)
        {
            swap(s);
            return *this;
        }
        ~string()
        {
            _size = _capacity = 0;
            delete[] _str;
            _str = nullptr;
        }
        //
        // iterator
        iterator begin()
        {
            return _str;
        }
        iterator end()
        {
            return _str + _size;
        }
        /
        // modify
        void push_back(char c)
        {
            if (_size == _capacity)
            {
                size_t NewCapacity = _capacity == 0 ? 4 : _capacity * 2;
                reserve(NewCapacity);
            }
            _str[_size] = c;
            _size++;
            _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;
        }
        /
        // capacity
        size_t size()const
        {
            return _size;
        }
        size_t capacity()const
        {
            return _capacity;
        }
        bool empty()const
        {
            return _size == 0;
        }
         void resize(size_t n, char c = '\0')
         {
             if (n > _size)
             {
                 reserve(n);
                 for (size_t i = _size; i < n; i++)
                 {
                     _str[i] = c;
                 }
                 _size = n;
                 _str[_size] = '\0';
             }
             else
             {
                 _str[n] = '\0';
                 _size = n;
             }
         }
        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 index)const
        {
            assert(index < _size);
            return _str[index];
        }
        // 返回c在string中第一次出现的位置
        size_t find(char c, size_t pos = 0) const
        {
            assert(pos < _size);
            for (size_t i = pos; i < _size; i++)
            {
                if (_str[i] == c)
                    return pos;
            }
            return npos;
        }
        // 返回子串s在string中第一次出现的位置
        size_t find(const char* s, size_t pos = 0) const
        {
            assert(pos < _size);
            const char* ptr = strstr(_str+pos, s);
            if (ptr == nullptr)
                return npos;
            else
                return _str - ptr;
        }
        // 在pos位置上插入字符c/字符串str,并返回该字符的位置
        string& insert(size_t pos, char c)
        {
            if (_size == _capacity)
            {
                size_t NewCapacity = _capacity == 0 ? 4 : _capacity * 2;
                reserve(NewCapacity);
            }
            size_t end = _size + 1;
            while (end > pos)
            {
                _str[end] = _str[end - 1];
                --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);
            }
            size_t end = _size + len;
            while (end > pos + len - 1)
            {
                _str[end] = _str[end - len];
                --end;
            }
            strncpy(_str + pos, str, len);
            _size += len;
            return *this;
        }
        // 删除pos位置上的元素,并返回该元素的下一个位置
        string& erase(size_t pos, size_t len = npos)
        {
            assert(pos < _size);
            if (len == npos || pos + len > _size)
            {
                _str[pos] = '\0';
                _size = pos;
            }
            else
            {
                strcpy(_str + pos, _str + pos + len);
                _size -= len;
            }
            return *this;
        }
    private:
        char* _str;
        size_t _capacity;
        size_t _size;
        const static size_t npos = -1;
    };
        void test1()
        {
            string s1("hello world");
            std::cout << s1.c_str() << std::endl;
            for (size_t i = 0; i < s1.size(); ++i)
            {
                s1[i]++;
            }
            std::cout << s1.c_str() << std::endl;
            string::iterator it1 = s1.begin();
            while (it1 != s1.end())
            {
                (*it1)--;
                ++it1;
            }
            std::cout << s1.c_str() << std::endl;
            for (auto ch : s1)
            {
                std::cout << ch << " ";
            }
            std::cout << std::endl;
        }
        void test2()
        {
            string s1("hello");
            s1 += ' ';
            s1 += '!';
            s1 += '!';
            s1 += "world hello world";
            cout << s1.c_str() << endl;
            string s2;
            s2 += 'x';
            cout << s2.c_str() << endl;
        }
        void test3()
        {
            string s1("helloworld");
            cout << s1.c_str() << endl;
            s1.insert(5, ' ');
            cout << s1.c_str() << endl;
            s1.insert(0, 'x');
            cout << s1.c_str() << endl;
            string s2("helloworld");
            cout << s2.c_str() << endl;
            s2.insert(5, " + ");
            cout << s2.c_str() << endl;
            s2.insert(0, "hello ");
            cout << s2.c_str() << endl;
            s2.insert(0, "x");
            cout << s2.c_str() << endl;
            string s3;
            s3.insert(0, "");
            cout << s3.c_str() << endl;
        }
        void test4()
        {
            string s1("hello hello world");
            s1.erase(0, 6);
            cout << s1.c_str() << endl;
            s1.erase(5);
            cout << s1.c_str() << endl;
        }
        void test5()
        {
            string s1("hello world");
            s1.resize(5);
            cout << s1.size() << endl;
            cout << s1.capacity() << endl;
            cout << s1.c_str() << endl << endl;
            string s2("hello world");
            //s2.resize(15);
            s2.resize(15, 'x');
            cout << s2.size() << endl;
            cout << s2.capacity() << endl;
            cout << s2.c_str() << endl << endl;
            string s3("hello world");
            s3.resize(20, 'x');
            cout << s3.size() << endl;
            cout << s3.capacity() << endl;
            cout << s3.c_str() << endl << endl;
        }
        void test6()
        {
            string s1("hello world");
            cout << s1 << endl;
            cout << s1.c_str() << endl;
            s1.insert(5, '\0');
            cout << s1.size() << endl;
            cout << s1.capacity() << endl;
            cout << s1 << endl;
            cout << s1.c_str() << endl;
            cin >> s1;
            cout << s1 << endl;
            string s2;
            cin >> s2;
            cout << s2 << endl;
            string s3;
            cin >> s3;
            cout << s3 << endl;
        }
        void test7()
        {
            string s1("hello world");
            string s2(s1);
            cout << s1 << endl;
            cout << s2 << endl;
            string s3("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
            s1 = s3;
            cout << s1 << endl;
            cout << s3 << endl;
        }
    }
test.cpp
#include "myString.h"
int main()
{
	//myString::test1();
	/*myString::test2();*/
	/*myString::test3();*/
	/*myString::test4();*/
	/*myString::test5();*/
	//myString::test6();
	myString::test7();
	return 0;
}


















![[golang gin框架] 20.Gin 商城项目-商品模块功能](https://img-blog.csdnimg.cn/img_convert/cba7ab1791d2d35e964d2689e80da790.png)
