#pragma once
#include <iostream>
#include <assert.h>
namespace Test
{
class string
{
public:
typedef char* iterator;
public:
string(const char* str = "")
{
if (nullptr == str){
str = "";
}
_size = strlen(str);
_capacity = _size;
_str = new char[_capacity + 1];
strcpy(_str, str);
}
string(size_t n, char ch)
: _str(new char[n + 1])
, _size(n)
, _capacity(n)
{
memset(_str, ch, n);
_str[_size] = '\0';
}
string(const string& s)
: _str(new char[s._capacity + 1])
, _capacity(s._capacity)
, _size(s._size)
{
strcpy(_str, s._str);
}
template<class Iterator>
string(Iterator first, Iterator last)
{
auto it = first;
size_t n = 0;
while (it != last){
++it, ++n;
}
_str = new char[n + 1];
_size = _capacity = n;
it = first;
for (size_t i = 0; i < n; ++i){
_str[i] = *it++;
}
_str[n] = '\0';
}
string& operator=(const string& s)
{
if (this != &s){
if (_str){
delete[] _str;
_str = nullptr;
}
size_t size = s.size();
_str = new char[size];
strcpy(_str, s._str);
_capacity = size;
}
return *this;
}
~string()
{
if (_str != nullptr){
delete[] _str;
_str = nullptr;
_size = 0;
_capacity = 0;
}
}
///
// 迭代器操作
iterator begin()
{
return _str;
}
iterator end()
{
return _str + _size;
}
///
// 容量相关
size_t size()const
{
return _size;
}
size_t capacity()const
{
return _capacity;
}
bool empty()const
{
return _size == 0;
}
void resize(size_t newsize, char ch = char())
{
size_t oldsize = size();
if (newsize > oldsize){
if (newsize > capacity()){
reserve(newsize);
}
memset(_str, ch, newsize - oldsize);
}
_size = newsize;
_str[_size] = '\0';
}
void reserve(size_t newcapacity)
{
size_t oldcapacity = capacity();
if (newcapacity > oldcapacity){
char* temp = new char[newcapacity];
strcpy(temp, _str);
delete[] _str;
_str = temp;
_capacity = newcapacity;
}
}
///
// 元素访问
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 push_back(char ch)
{
*this += ch;
}
string& operator+=(char ch)
{
if (size() == capacity()){
reserve(_capacity * 2);
}
_str[_size++] = ch;
_str[_size] = '\0';
}
// 加等字符串
string& operator+= (const char* str)
{
size_t len = strlen(str);
char* temp = new char[_size + len + 1];
strcpy(temp, _str);
strcat(temp, str);
delete[] _str;
_str = temp;
_size += len;
_capacity = _size;
return *this;
}
string& operator+=(string& s)
{
*this += s._str;
return *this;
}
string& insert(size_t pos, char ch);
string& erase(size_t pos);
void clear()
{
_size = 0;
_str[0] = '\0';
}
///
// 特殊操作
const char* c_str()const
{
return _str;
}
size_t find(char ch, size_t pos)
{
while (pos < _size)
{
if (_str[pos] == ch){
return pos;
}
++pos;
}
return npos;
}
size_t rfind(char ch, size_t pos = npos)
{
int cur = (pos == npos) ? _size - 1 : pos;
while (cur >= 0){
if (_str[cur] == ch){
return pos;
}
--cur;
}
return npos;
}
private:
char* _str;
size_t _size;
size_t _capacity;
static size_t npos;
};
static size_t npos = -1;
}
【C++】STL实现string
最新推荐文章于 2024-03-06 20:36:31 发布