string的模拟实现

简介: string的模拟实现

主要模拟代码


#pragma once
#include<iostream>
#include<assert.h>
using namespace std;
 
namespace ljp
{
  class string
  {
    friend void swap(string& s1, string& s2);
    friend istream& operator>>(istream& in, string& s);
    friend ostream& operator<<(ostream& out, 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);
    }
 
    //析构函数
    ~string()
    {
      delete[] _str;
      _str = nullptr;
      _size = _capacity = 0;
    }
    //拷贝构造
    string(const string& s)
    {
      string tem(s.str());
      swap(*this, tem);
    } 
    //赋值运算符重载
    string& operator=(string s) 
    {
      swap(*this,s);
      return *this;
    }
 
    //c_str
    const char* str() const
    {
      return _str;
    }
 
    //[]重载
    char& operator[](size_t pos)
    {
      assert(pos < _size);
      return _str[pos];
    }
 
    //const []重载
    const char& operator[](size_t pos) const
    {
      assert(pos < _size);
      return _str[pos];
    }
 
    //begin和end
    iterator begin() const
    {
      return _str;
    }
    iterator end() const
    {
      return _str + _size;
    }
 
    //size
    size_t size() const 
    {
      return _size;
    }
    //capacity
    size_t capacity() const
    {
      return _capacity;
    }
    //reserve一次开辟一定的空间
    void reserve(size_t n)
    {
      if (n > _capacity)
      {
        char* tem = new char[n + 1];
        strcpy(tem, _str);
        delete[] _str;
        _str = tem;
 
        _capacity = n;
      }
 
    }
    //pushhu_back
    void push_back(char ch)
    {
      if (_size == _capacity)
      {
        reserve(_capacity == 0 ? 4 : _capacity * 2);
      }
      _str[_size] = ch;
      ++_size;
      _str[_size] = '\0';
    }
 
    //append
    void append(const char*str)
    {
      //扩容
      size_t len = strlen(str);
      if (_size + len >= _capacity)
      {
        reserve(_size + len+1);
      }
      strcpy(_str + _size, str);
      _size += len;
 
    }
    //+=运算符重载
    string& operator+=(char ch)
    {
      push_back(ch);
      return *this;
    }
    string& operator+=(const char* str)
    {
      append(str);
      return *this;
    }
 
    //insert函数
    void insert(size_t pos, char ch)
    {
      assert(pos <= _size);
      if (_size == _capacity)
      {
        reserve(_capacity == 0 ? 4 : _capacity * 2);
      }
      size_t end = _size+1;
      while (end > pos)
      {
        _str[end] = _str[end-1];
        end--;
      }
      _str[pos] = ch;
      ++_size;
 
    }
    void insert(size_t pos, const char* str)
    {
      assert(pos <= _size);
      size_t len = strlen(str);
      if (_size + len >= _capacity)
      {
        reserve(_size + len+1);
      }
      size_t end = _size + len;
      //注意while的判断条件
      while (end > pos+len-1)
      {
        _str[end] = _str[end - len];
        end--;
      }
      strncpy(_str + pos, str, len);
      _size += len;
    }
 
    //erase
    void earse(size_t pos, size_t len = npos)
    {
      assert(pos < _size);
      if (len == npos || len >= _size-pos)
      {
        _str[pos] = '\0';
        _size = pos;
      }
      else
      {
        strcpy(_str + pos, _str + pos + len);
        _size -= len;
      }
    }
 
    //resize
    void resize(size_t n,char ch='\0')
    {
      if (n <= _size)
      {
        _str[n] = '\0';
        _size = n;
      }
      else
      {
        reserve(n);
        for (size_t i = _size; i < n; i++)
        {
          _str[i] = ch;
        }
        _str[n] = '\0';
        _size = n;
      }
    }
    //find查找
    size_t find(char ch, size_t pos=0)const
    {
      assert(pos < _size);
      for (size_t i = 0; i < _size; i++)
      {
        if (_str[i] == ch)
          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;
    }
 
    //substr
    string substr(size_t pos=0, size_t len = npos)
    {
      string sub;
      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';
    }
 
  private:
    char* _str = nullptr;
    size_t _size=0;
    size_t _capacity=0;
  public:
    static const  int  npos;
  };
  const int string::npos = -1;
 
  //swap交换
  void swap(string& s1,string& s2)
  {
    std::swap(s1._str, s2._str);
    std::swap(s1._size, s2._size);
    std::swap(s1._capacity, s2._capacity);
  }
  
  ostream& operator<<(ostream& out, string& s)
  {
    for (int i = 0; i < s.size(); i++)
    {
      out << s[i];
    }
    return out;
  }
 
  istream& operator>>(istream& in, string& s)
  {
    s.clear();
 
    char ch;
    ch = in.get();
    char buffer[128];
    size_t i = 0;
    while (ch != ' ' && ch != '\n')
    {
      buffer[i++] = ch;
      if (i == 127)
      {
        buffer[127] = '\0';
        s += buffer;
        i = 0;
      }
      ch = in.get();
    }
    if (i > 0)
    {
      buffer[i] = '\0';
      s += buffer;
    }
    return in;
  }
 
  istream& getline(istream& in, string& s)
  {
    s.clear();
 
    char ch;
    ch = in.get();
    char buffer[128];
    size_t i = 0;
    while (ch != '\n')
    {
      buffer[i++] = ch;
      if (i == 127)
      {
        buffer[127] = '\0';
        s += buffer;
        i = 0;
      }
      ch = in.get();
    }
    if (i > 0)
    {
      buffer[i] = '\0';
      s += buffer;
    }
    return in;
  }
 
  void test_string1()
  {
    string s1("abcdefg");
    const string s2("xxxxxxxxxxxx");
    cout << s1.str() << endl;
    cout <<  s2.str() << endl;
 
  }
  void test_string2()
  {
    //string s1("hello world");
    const string s1("xxxxxxxxxxxx");
 
    cout << "for循环遍历: ";
    for (size_t i = 0; i < s1.size(); i++)
    {
      //s1[i]++;
      cout << s1[i];
    }
    cout << endl;
 
    cout << "迭代器遍历: ";
    //string::iterator it1 = s1.begin();
    string::const_iterator it2 = s1.begin();
    while (it2 != s1.end())
    {
      //--*it;
      cout << *it2;
      it2++;
    }
    cout << endl;
 
    cout << "范围for遍历: ";
    for (auto i : s1)
    {
      cout << i;
    }
    cout << endl;
  }
  void test_string3()
  {
    string s1("hello world");
    s1.push_back(' ');
    s1.push_back('h');
    s1.push_back('e');
    s1.push_back('l');
    s1.push_back('l');
    s1.push_back('o');
    cout << s1.str() << endl;
  }
  void test_string4()
  {
    string s1("hello world");
    s1.append("lijinpeng");
    cout << s1.str() << endl;
 
  }
  void test_string5()
  {
    string s1("hello world");
    s1 += 'l';
    s1 += 'j';
    s1 += 'p';
    s1 += "xxxxxxxxxx";
    cout << s1.str() << endl;
  }
  void test_string6()
  {
    string s1("hello world");
    /*s1.insert(0, 'x');
    s1.insert(0, 'x');
    s1.insert(0, 'x');
    s1.insert(0, 'x');*/
    s1.insert(5, "xxxxxxxx");
    cout << s1.str() << endl;
    //s1.earse(2,7);
    //cout << s1.str() << endl;
 
  }
  void test_string7()
  {
    string s1("hello world");
    s1.resize(2);
    cout << s1.str() << endl;
    string s2("hello world");
    s2.resize(17,'x');
    cout << s2.str() << endl;
 
  }
  void test_string8()
  {
    string s1("hello world");
    string s2(s1);
    string s3 = s1;
    cout << s1.str() << endl;
    cout << s2.str() << endl;
    cout << s3.str() << endl;
 
  }
  void test_string9()
  {
    string s1("hello world");
    string s2("lijinpeng");
    cout << s1.str() << endl;
    cout << s2.str() << endl;
    swap(s1, s2);
    cout << s1.str() << endl;
    cout << s2.str() << endl;
  }
  void test_string10()
  {
    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.str() << endl;
    }
 
    // strchar
    size_t i2 = url1.find('/', i1 + 3);
    if (i2 != string::npos)
    {
      domain = url1.substr(i1 + 3, i2 - (i1 + 3));
      cout << domain.str() << endl;
 
      uri = url1.substr(i2 + 1);
      //cout << uri.str() << endl;
    }
 
    // strstr  
    size_t i3 = url1.find("baidu");
    cout << i3 << endl;
  }
  void test_string11()
  {
    string s1;
    getline(cin, s1);
    //cin >> s1;
    cout << s1;
  }
  
}


test测试代码

#define _CRT_SECURE_NO_WARNINGS 1
#include"String.h"
 
 
int main()
{
  ljp::test_string1();
  ljp::test_string2();
  ljp::test_string3();
  ljp::test_string4();
  ljp::test_string5();
  ljp::test_string6();
  ljp::test_string7();
  ljp::test_string8();
  ljp::test_string9();
  ljp::test_string10();
  ljp::test_string11();
 
  
  return 0;
}


相关文章
|
存储 C语言 C++
string的使用和模拟实现-1
string的使用和模拟实现
|
2月前
|
C++ 容器
|
5月前
|
编译器 程序员 C语言
【C++】string模拟实现
这篇博客探讨了自定义实现C++ `string` 类的关键功能,包括构造、拷贝构造、赋值运算符重载及析构函数。作者强调了理解并实现这些功能对于面试的重要性。博客介绍了`string` 类的头文件`string.h`,其中定义了迭代器、基本成员函数如`swap()`、`size()`、`c_str()`等,并提到了深拷贝概念。此外,还展示了构造函数、析构函数和赋值运算符的实现,以及迭代器的定义与使用。博客还包括对C语言字符串函数的引用,以辅助读者理解实现细节。
|
5月前
|
C语言 C++
【C++】string模拟实现(下)
本文档介绍了自定义`string`类的一些关键功能实现,包括`reserve()`用于内存管理,`push_back()`和`append()`添加字符或字符串,运算符`+=`的重载,以及`insert()`, `erase()`进行插入和删除操作。此外,还涵盖了`find()`查找函数,字符串的比较运算符重载,`substr()`获取子串,`clear()`清除内容,以及流插入和提取操作。常量`npos`用于表示未找到的标记。文档以代码示例和运行结果展示各功能的使用。
|
6月前
|
算法 C++
【c++】string模拟实现(1)
【c++】string模拟实现(1)
134 0
|
6月前
|
C语言 C++
【c++】string模拟实现(2)
【c++】string模拟实现(2)
25 0
|
7月前
|
编译器 C++
【C++】模拟实现string
【C++】模拟实现string
|
7月前
|
存储 编译器 C++
【C++】——string的模拟实现
【C++】——string的模拟实现
|
7月前
|
编译器 C语言 C++
string的模拟实现
string的模拟实现
76 0
|
7月前
string的模拟(下)
string的模拟(下)
54 1