C++ String类的模拟实现

string类(了解)

1. 字符串是表示字符序列的类
2. 标准的字符串类提供了对此类对象的支持,其接口类似于标准字符容器的接口,但添加了专门用于操作单字节字符字符串的设计特性。
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<char, char_traits, allocator> string;
4. 不能操作多字节或者变长字符的序列。

string的具体接口如下:
 

#pragma once
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<assert.h>
using namespace std;
 
namespace mystring
{
     class string
    {
        friend ostream& operator<<(ostream& _cout, const string& s);

        friend istream& operator>>(istream& _cin, bit::string& s);

    public:
        // 迭代器
        typedef char* iterator;
        typedef const char* const_iterator;

        const_iterator begin() const;
        const_iterator end() const;

        iterator begin();
        iterator end();
        
        // 返回c风格的字符串
        const char* c_str()const;
        
        // string()
        // 构造,拷贝构造及析构函数
        string(const char* str = "");//string(const char* str = "\0")
        string(const string& s);
        ~string();

        string& operator=(string& s);
        string& operator=(const string& s);

        // 返回pos位置的字符,const string类对象调用
        char& operator[](size_t index);
        const char& operator[](size_t index)const;

        void swap(string& s);

        // 从字符串pos位置开始往前找字符,返回该字符在字符串中的位置
        size_t find(char c, size_t pos = 0) const;
        size_t find(const char* sub, size_t pos = 0) const;

        // 返回字符串有效长度
        size_t size()const;
        // 返回空间大小
        size_t capacity()const;
        // 判空
        bool empty()const;
        // 将有效字符的个数该成n个,多出的空间用字符‘\0’填充
        void resize(size_t n, char c = '\0');
        // 为字符串预留空间
        void reserve(size_t n);
        
       
        void erase(size_t pos, size_t len = npos);
        void insert(size_t pos, char c);
        void insert(size_t pos, const char* str);

        // 在字符串后追加一个字符串
        void append(const char* str);

        // 在字符串后尾插字符
        void push_back(char c);

        // 在字符串后追加字符串str
        string& operator+=(char c);
        string& operator+=(const char* str);

        // 这个函数的功能是从pos位置开始截取长度为len的子串,如果len大于pos后面的数据个数就直接返回pos位置及其之后的数据。否则先给sub预留len个空间,然后通过遍历将从pos位置开始长度为len的字符尾插到sub中最后直接返回sub即可    
        string substr(size_t pos = 0, size_t len = npos);

        void clear();

    private:
        char* _str = nullptr;
        size_t _size = 0;
        size_t _capacity = 0;
    public:
        static const int npos;
    };
    const int string::npos = -1;

    void swap(string& x, string& y);
    bool operator<(const string& s1, const string& s2);
    bool operator<=(const string& s1, const string& s2);

    bool operator>(const string& s1, const string& s2);
    bool operator>=(const string& s1, const string& s2);

    bool operator==(const string& s1, const string& s2);
    bool operator!=(const string& s1, const string& s2);

    // 流插入和流提取
    ostream& operator<<(ostream& out, const string& s);
    istream& operator>>(istream& in, string& s);
    
}

迭代器:

        // 放在类外
        onst int string::npos = -1;       

         const_iterator begin() const
        {
            return _str;
        }

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

        iterator begin()
        {
            return _str;
        }

        iterator end()
        {
            return _str + _size;
        }

c_str:

        const char* c_str()const
        {
            return _str;
        }

构造函数:

 string(const char* str = "")
            :_size(strlen(str))
        {
            _capacity = _size;
            _str = new char[_capacity + 1];
            strcpy(_str, str);
        }

拷贝构造函数:

        // 传统写法
        string(const string& s)
		{
			_str = new char[s._capacity + 1];
			strcpy(_str, s._str);
			_size = s._size;
			_capacity = s._capacity;
		}

		// 现代写法
		string(const string& s)
		{
			string tmp(s._str);
			swap(tmp);
		}

析构函数:

         ~string()
        {
            delete[] _str;
            _str = nullptr;
            _size = _capacity = 0;
        }

赋值重载:

        // 传统写法
        string& operator=(const string& 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;
        }

    

operator [ ]:

        char& operator[](size_t index)
        {
            assert(index < _size);
            return _str[index];
        }

        const char& operator[](size_t index)const
        {
            assert(index < _size);
            return _str[index];
        }

void swap(string& s):

         void swap(string& s)
        {

            std::swap(_str, s._str);
            std::swap(_size, s._size);
            std::swap(_capacity, s._capacity);
        }

find 查找接口:

         size_t find(char c, size_t pos = 0) const
        {
            assert(pos < _size);
            for (int i = pos; i < _size; i++)
            {
                if (_str[i] == c)
                    return i;
            }
            return npos;
        }

        size_t find(const char* sub, size_t pos = 0) const
        {
            assert(pos < _size);
            const char* p = strstr(_str + pos, sub);
            if (p)
                return p - _str;
            else
                return npos;
        }

容量操作接口:

size:

        size_t size()const
        {
            return _size;
        }

capacity:

         size_t capacity()const
        {
            return _capacity;
        }

empty:

         bool empty()const
        {
            return _str;
        }

resize:

        void resize(size_t n, char c = '\0')
        {
            if (n <= _size)
            {
                _str[n] = '\0';
                _size = n;
            }
            else
            {
                reserve(n);
                for (int i = _size; i < n; i++)
                {
                    _str[i] = c;
                }
                _str[n] = '\0';
                _size = n;

            }
        }

reserve:

         void reserve(size_t n)
        {
            if (n > _capacity)
            {
                char* tmp = new char[n + 1];
                strcpy(tmp, _str);
                delete[] _str;
                _str = tmp;
                _capacity = n;
            }

修改及访问操作接口:

erase:

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

insert:

        void insert(size_t pos, char c)
        {
            assert(pos <= _size);
            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 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)//end - len +1 > pos
            {
                _str[end] = _str[end - len];
                end--;
            }
            strncpy(_str + pos, str, len);
            _size += len;
        }

append:

        void append(const char* str)
        {
            insert(_size, str);
        }

push_back:

        void push_back(char c)
        {
            insert(_size, c);
        }

operator+=:

        string& operator+=(char c)
        {
            push_back(c);
            return *this;
        }


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

substr:

        string substr(size_t pos = 0, size_t len = npos)
		{
			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;
		}

clear:

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

void swap(string& x, string& y):

     void swap(string& x, string& y)
    {
        x.swap(y);
    }

运算符重载:

    bool operator<(const string& s1, const string& s2)
    {
        int ret = strcmp(s1.c_str(), s2.c_str());
        return ret < 0;
    }

    bool operator<=(const string& s1, const string& s2)
    {
        return s1 < s2 || s1 == s2;
    }

    bool operator>(const string& s1, const string& s2)
    {
        return !(s1 <= s2);
    }

    bool operator>=(const string& s1, const string& s2)
    {
        return !(s1 < s2);
    }

    bool operator==(const string& s1, const string& s2)
    {
        int ret = strcmp(s1.c_str(), s2.c_str());
        return ret == 0;
    }

    bool operator!=(const string& s1, const string& s2)
    {
        return !(s1 == s2);
    }

流插入:

    ostream& operator<<(ostream& out, const string& s)
    {
        for (auto e : s)
        {
            out << e;
        }
        return out;
    }

流提取:

    istream& operator>>(istream& in, string& s)
    {
        s.clear();
        char ch;
        ch = in.get();
        size_t i = 0;
        char buff[128];
        while (ch != ' ' && ch != '\0')
        {
            buff[i++] = ch;
            if (i == 127)
            {
                buff[127] = '\0';
                s += buff;
                i = 0;
            }
            ch = in.get();

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

源代码:

#pragma once
#include<assert.h>
#include<iostream>
#include <string.h>

using namespace std;

namespace mystring
{
    class string

    {

        friend ostream& operator<<(ostream& _cout, const string& s);

        friend istream& operator>>(istream& _cin, bit::string& s);

    public:
        typedef char* iterator;
        typedef const char* const_iterator;


    public:

        const_iterator begin() const
        {
            return _str;
        }

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

        iterator begin()
        {
            return _str;
        }

        iterator end()
        {
            return _str + _size;
        }

        const char* c_str()const
        {
            return _str;
        }


        string(const char* str = "")
            :_size(strlen(str))
        {
            _capacity = _size;
            _str = new char[_capacity + 1];
            strcpy(_str, str);

        }

        string(const string& s)
        {
            string tmp(s._str);
            swap(tmp);

        }

        string& operator=(string& s)
        {
            swap(s);
            return *this;
        }

        //string& operator=(const string& s)
        //{
        //    string tmp(s);
        //    swap(tmp);
        //    return *this;
        //}


        ~string()
        {
            delete[] _str;
            _str = nullptr;
            _size = _capacity = 0;
        }


        char& operator[](size_t index)
        {
            assert(index < _size);
            return _str[index];
        }

        const char& operator[](size_t index)const
        {
            assert(index < _size);
            return _str[index];
        }

        void swap(string& s)
        {

            std::swap(_str, s._str);
            std::swap(_size, s._size);
            std::swap(_capacity, s._capacity);
        }

        size_t find(char c, size_t pos = 0) const
        {
            assert(pos < _size);
            for (int i = pos; i < _size; i++)
            {
                if (_str[i] == c)
                    return i;
            }
            return npos;
        }

        size_t find(const char* sub, size_t pos = 0) const
        {
            assert(pos < _size);
            const char* p = strstr(_str + pos, sub);
            if (p)
                return p - _str;
            else
                return npos;
        }

        size_t size()const
        {
            return _size;
        }

        size_t capacity()const
        {
            return _capacity;
        }

        bool empty()const
        {
            return _str;
        }

        void resize(size_t n, char c = '\0')
        {
            if (n <= _size)
            {
                _str[n] = '\0';
                _size = n;
            }
            else
            {
                reserve(n);
                for (int i = _size; i < n; i++)
                {
                    _str[i] = c;
                }
                _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;
            }

        }

        void push_back(char c)
        {
            insert(_size, c);
        }

        string& operator+=(char c)
        {
            push_back(c);
            return *this;
        }


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


        void append(const char* str)
        {
            insert(_size, str);
        }

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


        void insert(size_t pos, char c)
        {
            assert(pos <= _size);
            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 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)//end - len +1 > pos
            {
                _str[end] = _str[end - len];
                end--;
            }
            strncpy(_str + pos, str, len);
            _size += len;
        }
        
        string substr(size_t pos = 0, size_t len = npos)
		{
			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 clear()
        {
            _size = 0;
            _str[_size] = '\0';
        }

    private:
        char* _str = nullptr;
        size_t _size = 0;
        size_t _capacity = 0;
    public:
        static const int npos;
    };


    const int string::npos = -1;

    void swap(string& x, string& y)
    {
        x.swap(y);
    }

    bool operator==(const string& s1, const string& s2)
    {
        int ret = strcmp(s1.c_str(), s2.c_str());
        return ret == 0;
    }

    bool operator!=(const string& s1, const string& s2)
    {
        return !(s1 == s2);
    }


    bool operator<(const string& s1, const string& s2)
    {
        int ret = strcmp(s1.c_str(), s2.c_str());
        return ret < 0;
    }

    bool operator<=(const string& s1, const string& s2)
    {
        return s1 < s2 || s1 == s2;
    }

    bool operator>(const string& s1, const string& s2)
    {
        return !(s1 <= s2);
    }

    bool operator>=(const string& s1, const string& s2)
    {
        return !(s1 < s2);
    }


    ostream& operator<<(ostream& out, const string& s)
    {
        for (auto e : s)
        {
            out << e;
        }
        return out;
    }

    istream& operator>>(istream& in, string& s)
    {
        s.clear();
        char ch;
        ch = in.get();
        size_t i = 0;
        char buff[128];
        while (ch != ' ' && ch != '\0')
        {
            buff[i++] = ch;
            if (i == 127)
            {
                buff[127] = '\0';
                s += buff;
                i = 0;
            }
            ch = in.get();

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

}

测试代码:

#define _CRT_SECURE_NO_WARNINGS 1
#include"string.h"

//void test_string1()
//{
//	string s1("hello world");
//	string 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 string s3("xxxx");
//	for (size_t i = 0; i < s3.size(); i++)
//	{
//		//s3[i]++;
//		cout << s3[i] << " ";
//	}
//	cout << endl;
//
//
//}

//void test_string2()
//{
//	string s3("hello world");
//	for (auto ch : s3)
//	{
//		cout << ch << " ";
//	}
//	cout << endl;
//
//	string::iterator it3 = s3.begin();
//	while (it3 != s3.end())
//	{
//		*it3 -= 1;
//		cout << *it3 << " ";
//		++it3;
//	}
//	cout << endl;
//
//	const string s4("xxxx");
//	string::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()
//{
//	string 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;
//
//	string 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_string4()
//{
//	string s1("hello world");
//	cout << s1.c_str() << endl;
//
//	string s2(s1);
//	cout << s2.c_str() << endl;
//
//	s1[0] = 'x';
//
//	cout << s1.c_str() << endl;
//	cout << s2.c_str() << endl;
//
//	string s3("xxxxx");
//	s1 = s3;
//
//	cout << s1.c_str() << endl;
//	cout << s3.c_str() << endl;
//}

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

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

	string 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;
}

int main()
{

	test_string5();


	return 0;
}

自己实现字符串 class CMStringImp; class CMstring { public: explicit CMstring(void); ~CMstring(void); CMstring(LPCTSTR lpszstr); CMstring(const CMstring& lpszstr); CMstring& operator = (const CMstring& lpszstr); operator LPCTSTR() const; bool operator == (const CMstring&) const; bool operator != (const CMstring&) const; bool operator < (const CMstring&) const; TCHAR operator[] (int nIndex) const; TCHAR& operator[] (int nIndex); CMstring& operator += (LPCTSTR pStr); CMstring& operator += (TCHAR ch); friend CMstring operator+(const CMstring& str1, const CMstring& str2); friend CMstring operator+(const CMstring& str1, LPCTSTR lpszstr); friend CMstring operator+(const CMstring& str1, TCHAR ch); friend CMstring operator+(TCHAR ch, const CMstring& str1); friend CMstring operator+(LPCTSTR lpszstr, const CMstring& str1); // friend wostream operator <<(wostream &is;,const CMstring &str;); public: LPCTSTR GetData() const; bool IsEmpty() const; TCHAR GetAt(int) const; TCHAR& GetAt(int); int GetLength() const; int Compare(const CMstring&) const; int CompareNoCase(const CMstring&) const; int Find(TCHAR ch, int nStart = 0) const; int Find(LPCTSTR pStr, int nStart = 0) const; int ReverseFind(TCHAR ch) const; int ReverseFind(LPCTSTR pStr) const; CMstring Right(int nCount) const; CMstring Left(int nCount ) const; public: CMstring& MakeLower(); CMstring& MakeUpper(); CMstring& MakeReverse(); int Replace(TCHAR chOld, TCHAR chNew); int Replace(LPCTSTR pszOld, LPCTSTR pszNew); int Insert(int iIndex, TCHAR ch); void Format(LPCTSTR lpszFormat, ...); private: CMStringImp* m_pImp; };
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值