C++之string类模版的模拟实现

一、实现代码

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

namespace lee
{
    class string
    {
        friend ostream& operator<<(ostream& _cout, const lee::string& s);
        friend istream& operator>>(istream& _cin, lee::string& s);
    public:
        typedef char* iterator;
        typedef const char* const_iterator;
           //
        string(const char* str = "")
        {
            _size = strlen(str);
            _capacity = _size;
            _str = new char[_capacity + 1];
            //strcpy(_str, str);
            memcpy(_str, str, _size + 1);
        }
        string(const string& s)
        {
            _str = new char[s._capacity + 1];
            //strcpy(_str, s._str);
            memcpy(_str, s._str, s._size + 1);
            _size = s._size;
            _capacity = s._capacity;
        }
        void swap(string& s)
        {
            std::swap(_str, s._str);
            std::swap(_size, s._size);
            std::swap(_capacity, s._capacity);
        }
        string& operator=(string s)
        {
            swap(s);
            return *this;
        }
        ~string()
        {
            delete[] _str;
            _str = nullptr;
            _size = _capacity = 0;
        }
     
     
            // iterator
        iterator begin()
        {
            return _str;
        }
        iterator end()
        {
            return _str + _size;
        }

        const_iterator begin() const
        {
            return _str;
        }
        const_iterator end() const
        {
            return _str + _size;
        }
            /
            // modify
        void push_back(char c)
        {
            if (_size == _capacity)
            {
                reserve(_capacity == 0 ? 4 : _capacity * 2);
            }
            _str[_size++] = c;
            _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);
            }
            memcpy(_str + _size, str,len+1);
            _size += len;
        }
        string& operator+=(const char* str)
        {
            append(str);
            return *this;
        }
        void clear()
        {
            _str[0] = '\0';
            _size = 0;
        }
        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)
            {
                _size = n;
                _str[_size] = '\0';
            }
            else
            {
                reserve(n);
                for (size_t i = _size; i < n; i++)
                {
                    _str[i] = c;
                }
                _size = n;
                _str[_size] = '\0';
            }
        }
        void reserve(size_t n)
        {
            if (n > _capacity)
            {
                char* tmp = new char[n + 1];
               // strcpy(tmp, _str);
                memcpy(tmp, _str, _size + 1);
                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];
        }
        /
        //relational operators
        bool operator<(const string& s) const
        {
            //按最小字符串的长度比较
            int ret = memcmp(_str, s._str, _size < s._size ? _size : s._size);

            //三种情况:
            // "hello" "hello"   false
            // "helloxx" "hello" false
            // "hello" "helloxx" true
            return (ret == 0) ? (_size < s._size) : (ret < 0);
            
        }
        bool operator==(const string& s)
        {
            return _size == s._size
                && memcmp(_str, s._str, _size) == 0;
        }
        bool operator<=(const string& s)
        {
            return *this < s || *this == s;
        }
        bool operator>(const string& s)
        {
            return !(*this <= s);
        }
        bool operator>=(const string& s)
        {
            return !(*this < s);
        }

        bool operator!=(const string& s)
        {
            return !(*this == s);
        }
        // 返回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 i;
            }
            return npos;
        }
        // 返回子串s在string中第一次出现的位置
        size_t find(const char* str, size_t pos = 0) const
        {
            assert(pos < _size);
            const char* ptr = strstr(_str + pos, str);
            if (ptr)
            {
                return ptr - _str;
            }
            else
                return npos;
        }
        // 在pos位置上插入字符c/字符串str,并返回该字符的位置
        void insert(size_t pos, size_t n,char c)
        {
            assert(pos <= _size);
            if (_size + n > _capacity)
            {
                reserve(_size + n);
            }
            size_t end = _size;
            //end!=npos防止int整形提升到size_t导致死循环
            while (end >= pos && end != npos)
            {
                _str[end + n] = _str[end];
                --end;
            }
            for (size_t i = 0; i < n; i++)
            {
                _str[pos + i] = c;
            }
            _size += n;
        }
        void insert(size_t pos, const char* str)
        {
            assert(pos <= _size);
            size_t len = strlen(str);
            if (_size + len > _capacity)
            {
                reserve(_size + len);
            }
            //end!=npos防止int整形提升到size_t导致死循环
            size_t end = _size;
            while (end >= pos && end != npos)
            {
                _str[end + len] = _str[end];
                --end;
            }
            for (size_t i = 0; i < len; i++)
            {
                _str[pos + i] = str[i];
            }
            _size += len;
        }
        // 删除pos位置上的元素,并返回该元素的下一个位置
        void erase(size_t pos, size_t len=npos)
        {
            assert(pos <= _size);
            if (len == npos || pos + len >= _size)
            {
                _str[pos] = '\0';
                _size = pos;
            }
            else
            {
                size_t end = pos + len;
                while (end <= _size)
                {
                    _str[pos++] = _str[end++];
                }
                _size -= len;

            }
        }
        string substr(size_t pos = 0, size_t len = npos)
        {
            assert(pos < _size);
            size_t n = len; 
            if (len == npos || pos + len > _size)
            {
                n = _size - pos;    
            }
            string tmp;
            tmp.reserve(n);
            for (size_t i = pos; i < pos + n; i++)
            {
                tmp += _str[i];
            }
            return tmp;
        }
    private:
        char* _str;
        size_t _capacity;
        size_t _size;
    public:
        const static size_t npos;
    };
    const size_t string::npos = -1;
    ostream& operator<<(ostream& _cout, const lee::string& s)
    {
        for (auto ch : s)
        {
           _cout << ch;
        }
        return _cout;
    }
    istream& operator>>(istream& _cin, lee::string& s)
    {
        //先清空原来的缓冲区
        s.clear();
        //使用get才能得到空格
        char ch = _cin.get();
        //处理前缓冲区前面的空格或者换行
        while (ch == ' ' || ch == '\n')
        {
            ch = _cin.get();
        }
        //使用数组减少+=时reserve的次数(空间换时间)
        char buff[128];
        int i = 0;
        while (ch != ' ' && ch != '\n')
        {
            buff[i++] = ch;
            if (i == 127)
            {
                buff[i] = '\0';
                s += buff;
                i = 0;
            }
            ch = _cin.get();
        }
        if (i != 0)
        {
            buff[i] = '\0';
            s += buff;
        }
        return _cin;
    }
};

二、测试代码

#define _CRT_SECURE_NO_WARNINGS 1
#include"string.h"

void test1()
{
	lee::string s1("hello world");
	cout << s1.c_str() << endl;
	lee::string s2;
	cout << s2.c_str() << endl;

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

	const lee::string s3("hello world");
	s3[0];

	auto cit = s3.begin();
	while (cit != s3.end())
	{
		cout << *cit << " ";
		++cit;
	}
	cout << endl;

	lee::string::iterator it = s1.begin();
	while (it != s1.end())
	{
		*it += 1;
		cout << *it << " ";
		++it;
	}
	cout << endl;

	for (auto ch : s1)
	{
		cout << ch << " ";
	}
	cout << endl;
}
void test2()
{
	lee::string s1("hello world");
	cout << s1.c_str() << endl;

	s1.push_back(' ');
	s1.push_back('$');
	s1.append("hello lee");
	cout << s1.c_str() << endl;

	lee::string s2("hello world");
	cout << s2.c_str() << endl;

	s2 += ' ';
	s2 += '$';
	s2 += "hello lee";
	cout << s2.c_str() << endl;
}
void test3()
{

	lee::string s1("hello world");
	s1.insert(5, 3, '$');
	cout << s1.c_str() << endl;

	s1.insert(0, 3, '#');
	cout << s1.c_str() << endl;

	lee::string s2("hello world");
	s2.insert(5, " amazing");
	cout << s2.c_str() << endl;


}
void test4()
{
	lee::string s1("hello world");
	cout << s1.c_str() << endl;
	s1.erase(1, 5);
	cout << s1.c_str() << endl;
	s1.erase(5, 35);
	cout << s1.c_str() << endl;
	s1.erase(2);
	cout << s1.c_str() << endl;
}
void test5()
{
	lee::string ur1 = "https://www.bilibili.com/";
	size_t pos1 = ur1.find("://");
	if (pos1)
	{
		lee::string protocol = ur1.substr(0, pos1);
		cout << protocol.c_str() << endl;
	}
	size_t pos2 = ur1.find('b', pos1 + 3);
	if (pos2)
	{
		lee::string domain = ur1.substr(pos1+3, pos2-(pos1+3));
		lee::string uri = ur1.substr(pos2 + 1);
		cout << domain.c_str() << endl;
		cout << uri.c_str() << endl;
	}
}
void test6()
{
	lee::string s("hello world");
	s.resize(8);
	cout << s.c_str() << endl;
	cout << s << endl;

	s.resize(13, 'x');
	cout << s.c_str() << endl;
	cout << s << endl;

	s.resize(20, 'y');
	cout << s.c_str() << endl;
	cout << s << endl;

	 //c的字符数组,以\0为终止算长度
	 //string不看\0,以size为终止算长度

	lee::string ss("hello world");
	ss += '\0';
	ss += "!!!!!!!!!!";
	cout << ss.c_str() << endl;
	cout << ss << endl;

	lee::string copy(ss);
	cout << ss << endl;
	cout << copy << endl;

	ss += "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
	cout << ss << endl;
}
void test7()
{
	lee::string s;
	cin >> s;
	cout << s << endl;
}
void test8()
{
	lee::string s1("hello");
	lee::string s2("hello");
	cout << (s1 < s2) << endl;
	cout << (s1 > s2) << endl;
	cout << (s1 == s2) << endl << endl;


	lee::string s3("hello");
	lee::string s4("helloxxx");
	cout << (s3 < s4) << endl;
	cout << (s3 > s4) << endl;
	cout << (s3 == s4) << endl << endl;


	lee::string s5("helloxxx");
	lee::string s6("hello");
	cout << (s5 < s6) << endl;
	cout << (s5 > s6) << endl;
	cout << (s5 == s6) << endl << endl;
}
void test9()
{
	lee::string s1("hello");
	lee::string s2(s1);

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

	lee::string s3("xxxxxxxxxxxxx");
	s1 = s3;

	cout << s1 << endl;
	cout << s3 << endl;
}
int main()
{
	//test1();
	//test2();
	//test3();
	//test4();
	//test5();
	//test6();
	//test7();
	//test8();
	test9();
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值