C++STL(string类)


1.string类的介绍

废话少说,不那么繁琐的介绍了!就是跟字符有关!

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

  1. string是表示字符串的字符串类
  2. 该类的接口与常规容器的接口基本相同,再添加了一些专门用来操作string的常规操作。
  3. string在底层实际是:basic_string模板类的别名,typedef basic_string<char, char_traits, allocator>string;
  4. 不能操作多字节或者变长字符的序列。

2.string的基本用法

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

2.1 拷贝用法

在这里插入图片描述
更多用法可以进入网站:https://cplusplus.com/
在这里插入图片描述

2.2 遍历用法

①第一种遍历:for循环(下标+[])
在这里插入图片描述
注意:
在这里插入图片描述
②第二种遍历:迭代器
在这里插入图片描述
看上去好像第一种下标+[]更简单,不过这个迭代器才是主流,其可以遍历链表,顺序表等等!

当然迭代器还有反向迭代器

string::reverse_iterator it3=s3.rbegin();

在这里插入图片描述

③第三种遍历:范围for
在这里插入图片描述
其实这个范围for的底层是迭代器,所以说迭代器才是主流!

2.3 迭代器

在这里插入图片描述
当然也有const反向迭代器
const_reverse_iterator

2.4 容量

在这里插入图片描述

2.5 元素访问

在这里插入图片描述

2.6 元素修改

在这里插入图片描述

2.7 其他操作

在这里插入图片描述
在这里插入图片描述
其他类型的数据转为字符串,可以使用to_string
字符串转其他类型的数据,可以使用stod!
在这里插入图片描述

3.string类的底层(模拟实现)

3.1 搭个结构

class string1
{
public:
    string1(const char* str = " ")//(构造函数,函数的作用是构造一个string1对象)
        :_size(strlen(str))
    {
        _capacity = _size;
        _str = new char[_capacity + 1];
        strcpy(_str, str);
    }
    
 ~string1()//析构函数,清理资源
    {
        delete[] _str;
        _str = nullptr;
        _size = _capacity = 0;
        cout << "~string1(析构清理已完成)" << endl;
    }
private://成员变量
    char* _str;//字符串
    size_t _capacity;//容量
    size_t _size;//字符串的长度
public:
    static const int npos;//对于类型为 size_t 的元素具有最大可能值。
    //此值在字符串的成员函数中用作 len(或 sublen)参数的值时,表示“直到字符串的末尾”。
    };

3.2 拷贝构造

    string1(const string1& s) //(拷贝构造函数)s2(s1)
    {
        this->_str = new char[s._capacity + 1];
        strcpy(_str, s._str);
        _size = s._size;
        _capacity = s._capacity;
    }

3.3 操作符重载operator=,operator+=

  string1& operator=(const string1& s)//(为字符串分配一个新的值,替换当前内容) s1=s3
    {
        char* tmp = new char[s._capacity + 1];
        strcpy(tmp, _str);
        delete _str;
        _str = tmp;
        _size = s._size;
        _capacity = s._capacity;

        return *this;
    }
    
 string1& operator+=(char c)//通过在字符串的当前值末尾追加其他字符来扩展字符串:
    {
        push_back(c);
        return *this;
    }

3.4 resize

void string1::resize(size_t n, char c)//n<size,保留前n位删除别的;size<n<capacity,剩余部分插入\0;n>capacity,可以自定义后面插入什么字符
{
    if (n <= _size)
    {
        _str[n] = '\0';
        _size = n;
    }
    else
    {
        reserve(n);//更改容量(扩容,但不会缩容)
        for (size_t i = _size; i < n; i++)
        {
            _str[i] = c;
        }
        _str[n] = '\0';
        _size = n;
    }
}

3.5 reserve

void string1::reserve(size_t n)//更改容量(扩容,但不会缩容)
{
    if (n > _capacity)
    {
        char* tmp = new char[n + 1];
        strcpy(tmp, _str);
        delete[] _str;
        _str = tmp;

        _capacity = n;
    }
}

3.6 push_back

void string1::push_back(char c)//将字符 c 追加到字符串的末尾,只能追加单个字符。
{
    if (_size == _capacity)
    {
        reserve(_capacity == 0 ? 4 : 2 * _capacity);//如果一开始capacity就是0就没法搞了,所以要先用个三目
    }
    _str[_size] = c;
    ++_size;
    _str[_size] = '\0';
}

3.7 append

void string1::append(const char* str)//通过在字符串的当前值末尾追加其他字符来扩展字符串:允许追加多个参数值
{
    size_t len = strlen(str);
    if (_size + len > _capacity)
        reserve(_size + len);

    strcpy(_str + _size, str);
    _size = _size + len;
}

3.8 insert

void string1::insert(size_t pos, char c)//在某个位置插入一个字符
{
    assert(pos <= _size);

    // 扩容2倍
    if (_size == _capacity)
    {
        reserve(_capacity == 0 ? 4 : 2 * _capacity);
    }

    size_t end = _size + 1;
    while (end > pos)
    {
        _str[end] = _str[end - 1];
        --end;
    }

    _str[pos] = c;
    ++_size;
}

void string1::insert(size_t pos, const char* str)//在某个位置插入字符串
{
    assert(pos <= _size);
    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;
}

3.9 erase

void string1::erase(size_t pos, size_t len)//擦除部分字符串,减少其长度:
{
    assert(pos < _size);

    if (len == npos || len >= _size - pos)
    {
        _str[pos] = '\0';
        _size = pos;
    }
    else
    {
        strcpy(_str + pos, _str + pos + len);
        _size = _size - len;
    }
}

3.10 等等等等,这里附上完整代码

string.h:

#pragma once
#define _CRT_SECURE_NO_WARNINGS 1

#include <iostream>
using namespace std;
#include <assert.h>

namespace my_string
{
    class string1
    {
        friend ostream& operator<<(ostream& _cout, const string& s)
        {
            for (auto ch : s)
            {
                _cout << ch;
            }
            return _cout;
        }

        friend istream& operator>>(istream& _cin, string& s)
        {
            s.clear();

            char ch;
            //in >> ch;
            ch = _cin.get();
            char buff[128];
            size_t i = 0;
            while (ch != ' ' && ch != '\n')
            {
                buff[i++] = ch;
                // [0,126]
                if (i == 127)
                {
                    buff[127] = '\0';
                    s += buff;
                    i = 0;
                }
                ch = _cin.get();
            }

            if (i > 0)
            {
                buff[i] = '\0';
                s += buff;
            }
            return _cin;
        }

    public:
        typedef char* iterator;
        typedef const char* const_iterator;
    public:
        string1(const char* str = " ")//(构造函数,函数的作用是构造一个string1对象)
            :_size(strlen(str))
        {
            _capacity = _size;
            _str = new char[_capacity + 1];
            strcpy(_str, str);
        }

        string1(const string1& s) //(拷贝构造函数)s2(s1)
        {
            this->_str = new char[s._capacity + 1];
            strcpy(_str, s._str);
            _size = s._size;
            _capacity = s._capacity;
        }

        string1& operator=(const string1& s)//(为字符串分配一个新的值,替换当前内容) s1=s3
        {
            char* tmp = new char[s._capacity + 1];
            strcpy(tmp, _str);
            delete _str;
            _str = tmp;
            _size = s._size;
            _capacity = s._capacity;

            return *this;
        }

        ~string1()//析构函数,清理资源
        {
            delete[] _str;
            _str = nullptr;
            _size = _capacity = 0;
            cout << "~string1(析构清理已完成)" << endl;
        }
        //
        // iterator

        const_iterator begin() const
        {
            return _str;
        }

        const_iterator end() const
        {
            return _str + _size;
        }

        iterator begin()
        {
            return _str;
        }

        iterator end()
        {
            return _size + _str;
        }
        /
        // modify
        void push_back(char c);

        string1& operator+=(char c)//通过在字符串的当前值末尾追加其他字符来扩展字符串:
        {
            push_back(c);
            return *this;
        }

        void append(const char* str);

        string1& operator+=(const char* str)
        {
            append(str);
            return *this;
        }

        void clear();
        void swap(string1& s);
        const char* c_str()const //用于返回一个指向以空字符结尾的字符数组(C风格字符串)的指针。
        {
            return _str;
        }
        /
        // capacity
        size_t size()const
        {
            return _size;
        }

        size_t capacity()const
        {
            return _capacity;
        }

        bool empty()const
        {
            if (_size == 0)
                return 0;
            else
                return 1;
        }
        void resize(size_t n, char c = '\0');
        void reserve(size_t n);
        /
        // access
        char& operator[](size_t pos)//返回字符串中pos位置处字符的引用
        {
            assert(pos < _size);
            return _str[pos];
        }

        const char& operator[](size_t pos)const
        {
            assert(pos < _size);
            return _str[pos];
        }
        public:
        /
        //relational operators
        bool operator<(const string1& s);
        bool operator<=(const string1& s);
        bool operator>(const string1& s);
        bool operator>=(const string1& s);
        bool operator==(const string1& s);
        bool operator!=(const string1& s);

        // 返回c在string1中第一次出现的位置
        size_t find(char c, size_t pos = 0) const;
        // 返回子串s在string1中第一次出现的位置
        size_t find(const char* s, size_t pos = 0) const;
        // 在pos位置上插入字符c/字符串str,并返回该字符的位置
        void insert(size_t pos, char c);
        void insert(size_t pos, const char* str);
        // 删除pos位置上的元素,并返回该元素的下一个位置
        void erase(size_t pos, size_t len = npos);
        string substr(size_t pos = 0, size_t len = npos);
    private://成员变量
        char* _str;//字符串
        size_t _capacity;//容量
        size_t _size;//字符串的长度

    public:
        static const int npos;//对于类型为 size_t 的元素具有最大可能值。
        //此值在字符串的成员函数中用作 len(或 sublen)参数的值时,表示“直到字符串的末尾”。

    };
    extern const int npos;
}

string.cpp:

#include "string.h"
#define _CRT_SECURE_NO_WARNINGS 1
using namespace my_string;
const int string1::npos = -1;

void string1::resize(size_t n, char c)//n<size,保留前n位删除别的;size<n<capacity,剩余部分插入\0;n>capacity,可以自定义后面插入什么字符
{
    if (n <= _size)
    {
        _str[n] = '\0';
        _size = n;
    }
    else
    {
        reserve(n);//更改容量(扩容,但不会缩容)
        for (size_t i = _size; i < n; i++)
        {
            _str[i] = c;
        }
        _str[n] = '\0';
        _size = n;
    }
}

void string1::reserve(size_t n)//更改容量(扩容,但不会缩容)
{
    if (n > _capacity)
    {
        char* tmp = new char[n + 1];
        strcpy(tmp, _str);
        delete[] _str;
        _str = tmp;

        _capacity = n;
    }
}

void string1::push_back(char c)//将字符 c 追加到字符串的末尾,只能追加单个字符。
{
    if (_size == _capacity)
    {
        reserve(_capacity == 0 ? 4 : 2 * _capacity);//如果一开始capacity就是0就没法搞了,所以要先用个三目
    }
    _str[_size] = c;
    ++_size;
    _str[_size] = '\0';
}

void string1::append(const char* str)//通过在字符串的当前值末尾追加其他字符来扩展字符串:允许追加多个参数值
{
    size_t len = strlen(str);
    if (_size + len > _capacity)
        reserve(_size + len);

    strcpy(_str + _size, str);
    _size = _size + len;
}

void string1::insert(size_t pos, char c)//在某个位置插入一个字符
{
    assert(pos <= _size);

    // 扩容2倍
    if (_size == _capacity)
    {
        reserve(_capacity == 0 ? 4 : 2 * _capacity);
    }

    size_t end = _size + 1;
    while (end > pos)
    {
        _str[end] = _str[end - 1];
        --end;
    }

    _str[pos] = c;
    ++_size;
}

void string1::insert(size_t pos, const char* str)//在某个位置插入字符串
{
    assert(pos <= _size);
    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;
}

void string1::erase(size_t pos, size_t len)//擦除部分字符串,减少其长度:
{
    assert(pos < _size);

    if (len == npos || len >= _size - pos)
    {
        _str[pos] = '\0';
        _size = pos;
    }
    else
    {
        strcpy(_str + pos, _str + pos + len);
        _size = _size - len;
    }
}

void string1::swap(string1& s)
{
    std::swap(_str, s._str);
    std::swap(_size, s._size);
    std::swap(_capacity, s._capacity);
}

size_t string1::find(char ch, size_t pos) const
{
    assert(pos < _size);

    for (size_t i = pos; i < _size; i++)
    {
        if (_str[i] == ch)
            return i;
    }

    return npos;
}

size_t string1::find(const char* sub, size_t pos) const
{
    assert(pos < _size);

    const char* p = strstr(_str + pos, sub);
    if (p)
    {
        return p - _str;
    }
    else
    {
        return npos;
    }
}

string string1::substr(size_t pos, size_t len)
{
    string sub;
    //if (len == npos || len >= _size-pos)
    if (len >= _size - pos)
    {
        for (size_t i = pos; i < _size; i++)
        {
            sub += _str[i];
        }
    }
    else
    {
        for (size_t i = pos; i < pos + len; i++)
        {
            sub += _str[i];
        }
    }

    return sub;
}

void string1::clear()
{
    _size = 0;
    _str[_size] = '\0';
}


bool string1::operator>(const string1& s) {
    int i = 0;
    while (_str[i] == s._str[i] && i < _size) {
        //当两个字符串字符相等时进入循环
        i++;
    }
    //不相等或遍历完了_str时退出循环
    if (i == _size) {
        //表示_str遍历完了,则肯定不大于
        return false;
    }
    return _str[i] > s._str[i] ? true : false;
}

bool string1::operator==(const string1& s) {
    int i = 0;
    while (_str[i] == s._str[i] && i < _size) {
        i++;
    }
    //遍历两个字符串,如果遍历完了,则表示相等
    if (i == _size && s._str[i] == '\0') {
        return true;
    }
    else {
        return false;
    }
}


bool string1::operator>=(const string1& s) {
    if (*this > s || *this == s) {
        return true;
    }
    return false;
}

bool string1::operator<(const string1& s) {
    if (!(*this >= s)) {
        return true;
    }
    return false;
}

bool string1::operator<=(const string1& s) {
    if (*this > s) {
        return false;
    }
    return true;
}

bool string1::operator!=(const string1& s) {
    if (*this == s) {
        return false;
    }
    return true;
}


main.cpp:

#define _CRT_SECURE_NO_WARNINGS 1

#include <iostream>
#include "string.h"
using namespace my_string;

void test_string1()
{
	string1 s1("hello world");
	string1 s2;
	cout << s1.c_str() << endl;
	cout << s2.c_str() << endl;

	for (size_t i = 0; i < s1.size(); i++)
	{
		s1[i]++;
	}
	cout << endl;

	// s1[100];

	for (size_t i = 0; i < s1.size(); i++)
	{
		cout << s1[i] << " ";
	}
	cout << endl;

	const string1 s3("xxxx");
	for (size_t i = 0; i < s3.size(); i++)
	{
		//s3[i]++;
		cout << s3[i] << " ";
	}
	cout << endl;

}

void test_string2()
{
	string1 s3("hello world");
	for (auto ch : s3)
	{
		cout << ch << " ";
	}
	cout << endl;

	string1::iterator it3 = s3.begin();
	while (it3 != s3.end())
	{
		*it3 -= 1;
		cout << *it3 << " ";
		++it3;
	}
	cout << endl;

	const string1 s4("xxxx");
	string1::const_iterator it4 = s4.begin();
	while (it4 != s4.end())
	{
		//*it4 += 3;
		cout << *it4 << " ";
		++it4;
	}
	cout << endl;

	for (auto ch : s4)
	{
		cout << ch << " ";
	}
	cout << endl;
}

void test_string3()
{
	string1 s3("hello world");
	s3.push_back('1');
	s3.push_back('2');
	cout << s3.c_str() << endl;
	s3 += 'x';
	s3 += "yyyyyy";
	cout << s3.c_str() << endl;

	string1 s4("hello string");
	s4.insert(5, 't');
	cout << s4.c_str() << endl;

	string1 s5("hello string");
	s5.insert(0, "safsfds");
	cout << s5.c_str() << endl;
}

void test_string4()
{
	string1 s1("hello world");
	cout << s1.c_str() << endl;

	s1.erase(6, 3);
	cout << s1.c_str() << endl;

	s1.erase(6, 30);
	cout << s1.c_str() << endl;

	s1.erase(3);
	cout << s1.c_str() << endl;

	string1 s2("hello world");
	cout << s2.c_str() << endl;

	s2.resize(5);
	cout << s2.c_str() << endl;

	s2.resize(20, 'x');
	cout << s2.c_str() << endl;
}

void test_string5()
{
	string1 s1("hello world");
	cout << s1.c_str() << endl;

	string1 s2(s1);
	cout << s2.c_str() << endl;

	s1[0] = 'x';

	cout << s1.c_str() << endl;
	cout << s2.c_str() << endl;

	string1 s3("xxxxx");
	s1 = s3;

	cout << s1.c_str() << endl;
	cout << s3.c_str() << endl;
}

void test_string6()
{
	string1 s1("hello world");
	cout << s1.c_str() << endl;

	s1.insert(6, "xxx");
	cout << s1.c_str() << endl;

	string1 s2("xxxxxxx");

	cout << s1.c_str() << endl;
	cout << s2.c_str() << endl;
	swap(s1, s2);
	s1.swap(s2);
	cout << s1.c_str() << endl;
	cout << s2.c_str() << endl;
}

void test_string7()
{
	string url1("https://legacy.cplusplus.com/reference/string/string/substr/");
	string url2("http://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=65081411_1_oem_dg&wd=%E5%90%8E%E7%BC%80%20%E8%8B%B1%E6%96%87&fenlei=256&rsv_pq=0xc17a6c03003ede72&rsv_t=7f6eqaxivkivsW9Zwc41K2mIRleeNXjmiMjOgoAC0UgwLzPyVm%2FtSOeppDv%2F&rqlang=en&rsv_dl=ib&rsv_enter=1&rsv_sug3=4&rsv_sug1=3&rsv_sug7=100&rsv_sug2=0&rsv_btype=i&inputT=1588&rsv_sug4=6786");

	string protocol, domain, uri;
	size_t i1 = url1.find(':');
	if (i1 != string::npos)
	{
		protocol = url1.substr(0, i1 - 0);
		cout << protocol.c_str() << endl;
	}

	// strchar
	size_t i2 = url1.find('/', i1 + 3);
	if (i2 != string::npos)
	{
		domain = url1.substr(i1 + 3, i2 - (i1 + 3));
		cout << domain.c_str() << endl;

		uri = url1.substr(i2 + 1);
		cout << uri.c_str() << endl;
	}
	size_t i3 = url1.find("baidu");
	cout << i3 << endl;
}


void test_string8()
{
	string s1("hello world");
	string s2("hello world");

	cout << (s1 == s2) << endl;

	cout << ("hello world" == s2) << endl;
	cout << (s1 == "hello world") << endl;

	cout << s1 << endl;
	cout << s2 << endl;

	cin >> s1 >> s2;

	cout << s1 << endl;
	cout << s2 << endl;
}

void test_string9()
{
	string s1;

	cin >> s1;
	cout << s1.capacity() << endl;
}

void test_string10()
{
	string s1("hello world");
	string s2(s1);

	cout << s1 << endl;
	cout << s2 << endl;
}


int main()
{
	test_string1();
	printf("第一个测试\n");

	test_string2();
	printf("第二个测试\n");

	test_string3();
	printf("第三个测试\n");

	test_string4();
	 printf("第四个测试\n");

	test_string5();
	 printf("第五个测试\n");
	test_string6();
	 printf("第六个测试\n");

	test_string7();
	printf("第七个测试\n");

	test_string8();
	printf("第八个测试\n");

	test_string9();
	printf("第九个测试\n");

	test_string10();
	printf("第十个测试\n");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Chris·Bosh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值