string的模拟实现

server/2024/9/24 5:32:38/

1.string.h代码

#pragma once
#include<assert.h>
namespace myh
{class string{friend ostream& operator<<(ostream& _cout, const myh::string& s);friend istream& operator>>(istream& _cin, myh::string& s);public:typedef char* iterator;typedef const char* const_iterator;// iteratoriterator begin(){return _str;}iterator end(){return _str + _size;}const_iterator begin() const{return _str;}const_iterator end() const{return _str + _size;}public:string(const char* str = ""):_size(strlen(str)){_capacity = _size;_str = new char[_capacity + 1];strcpy(_str, str);}string(const string& s):_size(s.size()){_capacity = _size;_str = new char[_capacity + 1];strcpy(_str, s._str);}/*string(const string& s)//现代写法1:_size(0),_capacity(0),_str(nullptr)//为了防止析构时候delete随机值{string tmp(s._str);swap(tmp);}*/string& operator=(const string& s){_size = s._size;_capacity = s._capacity;delete[] _str;_str = new char[_capacity + 1];strcpy(_str, s._str);return  *this;}//s1 = s2/*string& operator=(const string& s)现代写法1,结束的时候临时变量销毁,里面储存的原本s1中的数据也销毁了,{                                    //也相当于做了和传统写法里一样的事情if (this != &s){string tmp(s._str);swap(tmp);}return *this;}*//*	string& operator=(string tmp){swap(tmp);//这里不判断的原因是,都已经拷贝构造过开了空间了,判断不判断其实一样return *this;}*/~string(){_size = _capacity = 0;delete[]_str;_str = nullptr;}// modifyvoid push_back(char c){if (_capacity == _size){reserve(_capacity == 0 ? 4 : _capacity * 2);}_str[_size] = c;_size++;_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);}strcpy(_str + _size, str);_size = _capacity;}string& operator+=(const char* str){append(str);return *this;}void clear(){_str[0] = '\0';_size = 0;}void swap(string& s){std::swap(_size, s._size);std::swap(_capacity, s._capacity);std::swap(_str, s._str);}string substr(size_t pos, size_t len = npos){string s;size_t end = pos + len;if (len == npos || pos + len >= _size){len = _size - pos;end = _size;}s.reserve(len);for (size_t i = pos; i < end; i++){s += _str[i];}return s;}const char* c_str()const{return _str;}// capacitysize_t size()const{return _size;}size_t capacity()const{return _capacity;}bool empty()const{if (_size == 0)return true;else return false;}void resize(size_t n, char ch = '\0'){if (n <= _size){_str[n] = '\0';_size = n;}else{reserve(n);while (_size < n){_str[_size] = ch;++_size;}_str[_size] = '\0';}}void reserve(size_t n){if (n > _capacity){char* tmp = new char[n + 1];strcpy(tmp, _str);delete[]_str;_str = tmp;_capacity = n;}}// accesschar& operator[](size_t index){assert(index < _size && index >= 0);return _str[index];}const char& operator[](size_t index)const{assert(index < _size && index >= 0);return _str[index];}//relational operatorsbool operator<(const string& s){return strcmp(_str, s._str) < 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 strcmp(_str, s._str) == 0;}bool operator!=(const string& s){return !((*this) == s);}// 返回c在string中第一次出现的位置size_t find(char c, size_t pos = 0) const{for (int i = 0; i < _size; i++){if (_str[i] == c)return i;}return npos;}// 返回子串s在string中第一次出现的位置size_t find(const char* s, size_t pos = 0) const{const char* p = strstr(_str + pos, s);if (p){return p - _str;}else{return npos;}}// 在pos位置上插入字符c/字符串str,并返回该字符的位置void insert(size_t pos, char ch){assert(pos <= _size);if (_size == _capacity){reserve(_capacity == 0 ? 4 : _capacity * 2);}// 17:17size_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);}// 挪动数据int end = _size;while (end >= (int)pos){_str[end + len] = _str[end];--end;}strncpy(_str + pos, str, len);_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 begin = pos + len;while (begin <= _size){_str[begin - len] = _str[begin];++begin;}_size -= len;}}private:char* _str;size_t _capacity;size_t _size;const static size_t npos;};const size_t string::npos = -1;ostream& operator<<(ostream& _cout, const myh::string& s){for (size_t i = 0; i < s.size(); i++){_cout << s[i];}return cout;}istream& operator>>(istream& in, myh::string& s){s.clear();s.reserve(128);char ch;ch = in.get();while (ch != ' ' && ch != '\n'){s += ch;ch = in.get();}return in;}void test1(){string d1;//1string d2("hello myh");//1string d3(d2);//1d1 = d2;//1d1.push_back('a');//1d3.append("xyz");d2 += 'b';d2 += "cdefghijklmn";d1.clear();cout << d2.c_str() << endl;cout << d2.size() << endl;cout << d2.capacity() << endl;cout << d1.empty() << endl;cout << d2.empty() << endl;}void test2(){string d1("hello myh");const string d2(d1);d1.reserve(129);cout << d1[0] << endl;d1[0]++;cout << d1[0] << endl;cout << d2[1] << endl;cout << d1 << endl;cout << d2 << endl;int a, b, c, d, e, f;a = d1 > d2;b = d1 >= d2;c = d1 == d2;d = d1 < d2;d1[0]--;d1[1]--;e = d1 <= d2;f = d1 != d2;cout << a << b << c << d << e << f << endl;}void test3(){string s1("hello");string::iterator it = s1.begin();while (it != s1.end()){(*it)++;cout << *it << " ";++it;}cout << endl;for (auto ch : s1){ch++;cout << ch << " ";}cout << endl;cout << s1.c_str() << endl;for (auto& ch : s1){ch++;cout << ch << " ";}cout << endl;cout << s1.c_str() << endl;}void test4(){string d1("hello myh");cout << d1.find('m') << endl;cout << d1.find("lo") << endl;cout << d1.find('x') << endl;//d1.insert(1, '%');d1.insert(0, 'a');d1.insert(0, "i am");cout << d1 << endl;}void test5(){string d1("hello");string d2("world");//swap(d1, d2);//cout << d1 << endl;//cout << d2 << endl;//d1.resize(2);//cout << d1 << endl;;d1.resize(5);d1.resize(20, 'a');cout << d1 << endl;d1.erase(0, 3);cout << d1 << endl;d1.erase(5, 100);cout << d1 << endl;d1.erase(2);cout << d1 << endl;}
};

2.test.cpp

#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<vector>
#include<list>
#include<string>
using namespace std;#include"string.h"
int main()
{//myh::test1();//myh::test2();//myh::test3();//myh::test4();myh::test5();return 0;
}


http://www.ppmy.cn/server/99772.html

相关文章

apache几个重要概念和处理应对状态码的一些方法

一、apache几个重要概念 Apache 是一款开源 Web 服务器软件&#xff0c;在Web服务器&#xff08;如Apache HTTP Server&#xff09;和软件开发中&#xff0c;高度模块化、DSO&#xff08;Dynamic Shared Object&#xff09;和MPM&#xff08;Multi-Processing Module&#xff…

数据库逻辑删除时查询为什么不可用用like来进行查询?它们之间有什么转换吗?

1.首先可以查询我们的数据库字段&#xff0c;我们这里使用的是< bit(1) > 即只能存储一位&#xff0c;也只能是0或者1 2.在数据库操作中也被是涉及到逻辑删除时&#xff08;即使用某个字段来标识记录是否被删除&#xff0c;而不是从数据库中移除记录&#xff09;&#x…

【数据结构】五、树:6.平衡二叉树AVL

2.平衡二叉树AVL 文章目录 2.平衡二叉树AVL2.1定义2.2存储结构2.3查找2.4插入&#xff08;保持平衡&#xff09;2.4.1 LL平衡旋转(右单旋转)2.4.2 RR平衡旋转(左单旋转)2.4.3 LR平衡旋转(先左后右双旋转)2.4.4 RL平衡旋转(先右后左双旋转)2.4.5题解 2.5性能分析2.6删除 2.1定义…

http的发展历史,各版本的差异点,以及和https的区别

### HTTP的发展历史及各版本的差异点 HTTP/0.9 - **发布时间**&#xff1a;1991年 - **特点**&#xff1a; - 最初的HTTP协议版本&#xff0c;非常简单。 - 只支持GET方法&#xff0c;不支持请求头和响应头。 - 响应仅为纯文本&#xff0c;无法传输图片、音频等多媒体资…

llama factory 训练 TensorBoard 可视化

首先需要在 yaml 里设置两个参数&#xff1a; output_dir: /home/wangguisen/projects/LLaMA-Factory/weights/tensbox_demoreport_to: tensorboard logging_dir: /home/wangguisen/projects/LLaMA-Factory/weights/tensbox_demo/runs然后开始训练&#xff0c;在你的输出目录下…

LCM红外小目标检测

根据站内的matlab代码修改成python版本。 import numpy as np import matplotlib.pyplot as plt import cv2 from pylab import mpl# 设置中文显示字体 mpl.rcParams["font.sans-serif"] ["SimHei"]def LCM_computation(patch_LCM_in):row, col patch_L…

nodejs/node-sass/sass-loader三者版本对应关系(已解决)

基本前提&#xff1a;了解版本对应关系 示例&#xff1a; 我的nodejs&#xff1a;v14.21.3&#xff0c; 则package.json: "node-sass": "^4.14.1", "sass-loader": "^8.0.0",扩展&#xff1a; 查看node历史版本&#xff1a; Node.js…

java SPI实现类中注入spring bean对象

在项目中&#xff0c;用到了SPI来扩展一些功能&#xff0c;发现很多实现类中用到了bean对象&#xff0c;并且都是通过getBean的方式每次都去拿&#xff0c;感觉不是很方便&#xff0c;而且速度也没有直接使用对象快。 正好安排的工作就是优化那一块的代码&#xff0c;所以就改造…