C++ ─── string的完整模拟实现

一码归—码 2024-06-11 10:05:04 阅读 63

本博客实现了string的常见接口实现

下面是用到的一些函数,供大家回顾复习

改进1:流提取的改进

        原来的代码中流提取中是一个一个字符提取,扩容频率太快,消耗太多

采用buff的方式,buff在栈上,开空间快。

istream& operator>> (istream& is, string& str){str.clear();char buff[128];int i = 0;char ch = is.get();while (ch != ' ' && ch != '\n'){buff[i++] = ch;//0 - 126if (i == 127){buff[i] = '\0';str += buff;i = 0;}ch = is.get();}if (i != 0){buff[i] = '\0';str += buff;}return is;}

改进二:拷贝构造和赋值重载的改进

        传统写法就是1.开空间2.拷贝数据

        使用现代写法(利用构造函数)改进, 利用构造函数,两者实际效率一样但是现代写法更简单快捷

//bit::string s1(s2) 原来的写法string::string(const string& s){_str = new char[s._capacity+1];strcpy(_str, s._str);_size = s._size;_capacity = s._capacity;}//改进后//bit::string s2=s1;string::string(const string& s){string tmp(s._str);std::swap(tmp._str,_str);std::swap(tmp._size,_size);std::swap(tmp._capacity, _capacity);}string::string(const string& s){string tmp(s._str);swap(tmp);}注意有些平台s2没有初始化(this指针是随机制),s2与tmp交换后,tmp的_str为随机值,出了函数,tmp会调用析构函数就会崩解决方案:在.h文件定义中都加上缺省值例如:private://char _buff[16];char* _str=nullptr;size_t _size = 0;size_t _capacity = 0;

​//原来的 string& 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;}//改进后//s1 = s3string& string::operator=(const string& s){if (this != &s){string tmp(s._str);swap(tmp);}return *this;}string& string::operator=(string tmp){ swap(tmp); return *this;}​

string.h

#define _CRT_SECURE_NO_WARNINGS 1#pragma once#include<iostream>#include<assert.h>using namespace std;namespace bit{class string{public:typedef char* iterator;typedef const char* const_iterator;iterator begin();iterator end();const_iterator begin() const;const_iterator end() const;//string();string(const char* str = "");string(const string& s);string& operator=(const string& s);~string();const char* c_str() const;size_t size() const;size_t capacity() const;char& operator[](size_t pos);const char& operator[](size_t pos) const;void reserve(size_t n);void push_back(char ch);void append(const char* str);string& operator+=(char ch);string& operator+=(const char* str);void insert(size_t pos, char ch);//在pos前面插入void insert(size_t pos, const char* str);void erase(size_t pos = 0, size_t len = npos);//从pos开始删除size_t find(char ch, size_t pos = 0);size_t find(const char* str, size_t pos = 0);void swap(string& s);string substr(size_t pos = 0, size_t len = npos);bool operator<(const string& s) const;bool operator>(const string& s) const;bool operator<=(const string& s) const;bool operator>=(const string& s) const;bool operator==(const string& s) const;bool operator!=(const string& s) const;void clear();private://char _buff[16];char* _str;size_t _size;size_t _capacity;// //const static size_t npos = -1;// ֧//const static double N = 2.2;const static size_t npos;};istream& operator>> (istream& is, string& str);ostream& operator<< (ostream& os, const string& str);}

string.cpp

#define _CRT_SECURE_NO_WARNINGS 1#include"string.h"namespace bit{const size_t string::npos = -1;//重要string::iterator string::begin(){return _str;}string::iterator string::end(){return _str + _size;}string::const_iterator string::begin() const{return _str;}string::const_iterator string::end() const{return _str + _size;}//string();string::string(const char* str):_size(strlen(str)){_str = new char[_size + 1];//为'\0'也开位置strcpy(_str, str);_capacity = _size;}//string s1(s2)string::string(const string& s){_str = new char[s._capacity+1];strcpy(_str, s._str);_size = s._size;_capacity = s._capacity;}//s3=s1;//s1=s1;string& 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::~string(){delete[] _str;_str = nullptr;_size = _capacity = 0;}const char* string::c_str() const{return _str;}size_t string::size() const{return _size;}size_t string::capacity() const{return _capacity;}char& string::operator[](size_t pos){assert(pos < _size);return _str[pos];}const char& string::operator[](size_t pos) const{assert(pos < _size);return _str[pos];}void string::reserve(size_t n){if (n > _capacity){char* tmp = new char[n + 1];strcpy(tmp, _str);//复制字符串最后是'\0'delete[] _str;_str = tmp;_capacity = n;}}void string::push_back(char ch)//等价与+=(char ch){if (_size == _capacity){size_t newcapacity = _capacity == 0 ? 4 : _capacity * 2;reserve(newcapacity);}_str[_size++] = ch;_str[_size] = '\0';}void string::append(const char* str)//等价与+=(const char* ch){size_t len = strlen(str);if (_size == _capacity){size_t newcapacity = _capacity + len;reserve(newcapacity);}//直接从str末尾加入字符串strcpy(_str + _size, str);_size += len;}string& string::operator+=(char ch){push_back(ch);return (*this);}string& string::operator+=(const char* str){append(str);return (*this);}void string::insert(size_t pos, char ch){assert(pos < _size + 1);if (_size == _capacity){size_t newcapacity = _capacity == 0 ? 4 : _capacity * 2;reserve(newcapacity);}//此处有坑pos为无符号整形,end为有符号,在比较时有符号会被转成无符号,如果pos==0就会发生问题size_t end = _size + 1;//pos==0时,end最后为0,不会为-1(在无符号整形中-1为无穷大)while (end > pos){_str[end] = _str[end - 1];--end;}_str[end] = ch;_size++;}void string::insert(size_t pos, const char* str){size_t len = strlen(str);assert(pos < _size + len);if (_size == _capacity){size_t newcapacity = _capacity + len;reserve(newcapacity);}//此处有坑pos为无符号整形,end为有符号,在比较时有符号会被转成无符号,如果pos==0就会发生问题size_t end = _size + len;//pos==0时,end最后为0while (end > pos){_str[end] = _str[end - len];--end;}_size += len;//while (len)//{//_str[end + len - 1] = str[len-1];//--len;//}memcpy(_str + pos, str, len);}void string::erase(size_t pos, size_t len){assert(pos < _size);if (len > _size - pos){_str[pos] = '\0';_size = pos;}else{strcpy(_str + pos, _str + pos + len);_size -= len;}}size_t string::find(char ch, size_t pos){for (size_t i = pos; i < _size; ++i){if (_str[i] == ch){return i;}}return npos;//找不到返回-1}size_t string::find(const char* str, size_t pos){char* p = strstr(_str + pos, str);return p - _str;}//s1.swap(s2);void string::swap(string& s)//只需要交换s1和s2{std::swap(_str,s._str);std::swap(_size,s._size);std::swap(_capacity,s._capacity);}string string::substr(size_t pos, size_t len){// len大于后面剩余字符,有多少取多少if (len > _size - pos){string sub(_str + pos);return sub;}else{string sub;sub.reserve(len);for (size_t i = 0; i < len; i++){sub += _str[pos + i];}return sub;}}bool string::operator<(const string& s) const{return strcmp(_str, s._str) < 0;}bool string::operator>(const string& s) const{return !(*this <= s);}bool string::operator<=(const string& s) const{return *this < s || *this == s;}bool string::operator>=(const string& s) const{return !(*this < s) ;}bool string::operator==(const string& s) const{return strcmp(_str, s._str) == 0;}bool string::operator!=(const string& s) const{return !(*this == s);}void string::clear(){_str[0] = '\0';_size = 0;}istream& operator>> (istream& is, string& str){str.clear();char ch = is.get();while (ch != ' ' && ch != '\n'){str += ch;ch = is.get();}return is;}ostream& operator<< (ostream& os, const string& str){for (size_t i = 0; i < str.size(); i++){os << str[i];}return os;}}

test.cpp

#define _CRT_SECURE_NO_WARNINGS 1#include"string.h"void test_string1(){bit::string s1("hello csdn");bit::string s2;std::cout << s1.c_str() << std::endl;}void test_string2(){bit::string s1("hello csdn");s1[0] = 'X';std::cout << s1.c_str() << std::endl;}void test_string3(){bit::string s1("hello csdn");for (size_t i = 0; i < s1.size(); ++i){std::cout << s1[i] << " ";}std::cout << std::endl;bit::string::iterator it1 = s1.begin();while (it1 != s1.end()){std::cout << *it1 << " ";++it1;}std::cout << std::endl;for (auto& e : s1){e++;std::cout << e << " ";}std::cout << std::endl;bit::string s2;std::cout << s1.c_str() << std::endl;std::cout << s2.c_str();}void test_string4(){bit::string s1("hello csdn");cout << s1.capacity()<<endl;s1.reserve(30);cout <<s1.c_str()<< s1.capacity() << endl;s1.push_back('s');cout << s1.c_str() << s1.capacity() << endl;const char* str1 = "tr";s1.append(str1);cout << s1.c_str() << s1.capacity() << endl;s1.append(" 666老毕");cout << s1.c_str() << s1.capacity() << endl;}void test_string5(){bit::string s1("hello csdn");cout << s1.c_str() << endl;s1.insert(0,'x');cout << s1.c_str() << endl;s1.insert(0, "666");cout << s1.c_str() << endl;s1.erase(0,3);cout << s1.c_str() << endl;}void test_string6(){bit::string s1("hello csdn");size_t ret = s1.find('o');if (ret != -1){cout << ret << endl;}size_t ret2 = s1.find("cs");if (ret2 != -1){cout << ret2 << endl;}}void test_string7(){bit::string s1("hello csdn");bit::string s2("hello");cout << s1.c_str() << endl;cout << s2.c_str() << endl;s1.swap(s2);cout << s1.c_str() << endl;cout << s2.c_str() << endl;}void test_string8(){bit::string url("https://gitee.com/ailiangshilove/cpp-class/blob/master/%E8%AF%BE%E4%BB%B6%E4%BB%A3%E7%A0%81/C++%E8%AF%BE%E4%BB%B6V6/string%E7%9A%84%E6%8E%A5%E5%8F%A3%E6%B5%8B%E8%AF%95%E5%8F%8A%E4%BD%BF%E7%94%A8/TestString.cpp");size_t pos1 = url.find(':');bit::string url1 = url.substr(0, pos1 - 0);cout << url1.c_str() << endl;size_t pos2 = url.find('/', pos1 + 3);bit::string url2 = url.substr(pos1 + 3, pos2 - (pos1 + 3));cout << url2.c_str() << endl;bit::string url3 = url.substr(pos2 + 1);cout << url3.c_str() << endl;}void test_string9(){bit::string s1("hello world");cout << s1 << endl;cin >> s1;cout << s1 << endl;bit::string s3(s1);cout << s3 << endl;bit::string s2("hello BiMenghao");s3 = s2;cout << s3 << endl;}int main(){test_string9();return 0;}

\

这个博客如果对你有帮助,给博主一个免费的点赞就是最大的帮助❤

欢迎各位点赞,收藏和关注哦❤

如果有疑问或有不同见解,欢迎在评论区留言哦❤

后续我会一直分享双一流211西北大学软件(C,数据结构,C++,Linux,MySQL)的学习干货以及重要代码的分享



声明

本文内容仅代表作者观点,或转载于其他网站,本站不以此文作为商业用途
如有涉及侵权,请联系本站进行删除
转载本站原创文章,请注明来源及作者。