当前位置:网站首页>Introduction and Simulation Implementation of string class
Introduction and Simulation Implementation of string class
2022-07-19 11:39:00 【'pie pie'】
Catalog
2.string Class common interface
2.1. string Common constructions of class objects
2. 1string Class object capacity operation
2.3. string Class object modification operation
4.string The realization of the class
4.1 Deep and shallow copy problem
4.2.string Class common function implementation
1. Introduce
2.string Class common interface
2.1. string Common constructions of class objects

give an example :
vvoid test_string1()
{
string s1(10,'x');
string s2("hello world");
string s3(s2, 6, 3);// from s2 pass the civil examinations 6 Copy data from locations , If no length is specified , Then copy all the following data
string s4(s2.begin() + 1, s2.end());
cout << s1 << endl;
cout << s2 << endl;
cout << s3 << endl;
cout << s4 << endl;
}
int main()
{
test_string1();
return 0;
}
result :
xxxxxxxxxx
hello world
wor
ello world2. 1string Class object capacity operation



Add :resize,reserve Will not shrink , but resize Can reduce data , change size
2.3. string Class object modification operation

void test_string3()
{
string s1("http://www.com.cplusplus.com/reference/string/string/find/");
cout << s1.c_str() << endl;// obtain s1 String in
string s2 = s1.substr(5,5);// from s1 in pos Position copy Character , If no length is specified , Copy everything behind ;
cout << s2 << endl;
size_t pos1 = s1.rfind('f');// Find characters from back to front , Returns the subscript ,
size_t pos2 = s1.find("com", 12);// Subscript from front 12 Find string , Returns the subscript
cout << pos1 << " " << pos2 << endl;
}
result :
http://www.com.cplusplus.com/reference/string/string/find/
//www
53 25
string s;
getline(cin, s);// You can enter a string of characters , With spaces
cout << s << endl;3. summary :
string There are many functions in the class , And there are overloads , You can view the document :string - C++ Reference To learn
4.string The realization of the class
namespace LF
{
class string
{
public:
private:
char* _str;// Store string
size_t _size; // Number of valid characters
size_t _capacity; // The actual space to store valid characters
};
}4.1 Deep and shallow copy problem
First mask the copy constructor
namespace LF
{
class string
{
public:
typedef char* iterator;
typedef const char* const_iterator;
const_iterator begin() const
{
return _str;
}
const_iterator end() const
{
return _str + _size;
}
iterator begin()
{
return _str;
}
iterator end()
{
return _str + _size;
}
string(const char* str = "")// All default
: _size(strlen(str))
, _capacity(_size)
{
_str = new char[_capacity + 1];// to \0 Reserve space
strcpy(_str, str);
}
/*string(const string& s)// Mask this constructor
:_str(new char[strlen(s._str)+1])
{
strcpy(_str, s._str);
}*/
~string()// Destructor
{
if (_str)
{
delete[] _str;
}
}
const char* c_str() const// Returns the string ,const, Do not modify
{
return _str;
}
char& operator[](size_t pos)// Return value with &, The original data can be modified
{
assert(pos < strlen(_str));
return _str[pos];
}
const char& operator[](size_t pos) const// Do not modify the
{
assert(pos < _size);
return _str[pos];
}
size_t size() const
{
return _size;
}
size_t capacity() const
{
return _capacity;
}
private:
char* _str;// Store string
size_t _size; // Number of valid characters
size_t _capacity; // The actual space to store valid characters
};
}
void test_string1()
{
LF::string s1("hello");
LF::string s2(s1);
cout << s1.c_str() << endl;
cout << s2.c_str() << endl;
s1[2] = 'P';
cout << s1.c_str() << endl;
cout << s2.c_str() << endl;
}
int main()
{
test_string1();
return 0;
} result :
What is called here is the copy constructor generated by default , Finished is a shallow copy ,s1 The modification will affect s2, And will destruct the same space twice , Report errors .
4.2.string Class common function implementation
1. Capacity expansion
void reserve(size_t n)
{
if (n > _capacity)
{
char* tmp = new char[n + 1];
strcpy(tmp, _str);
delete[] _str;
_str = tmp;
_capacity = n;
}
}2. Expand and initialize
void resize(size_t n, char ch = '\0')
{
if (n < _size)
{
_size = n;
_str[_size] = '\0';
}
else
{
if (n > _capacity)
{
reserve(n);
}
for (size_t i = _size; i < n; ++i)
{
_str[i] = ch;
}
_size = n;
_str[_size] = '\0';
}
}
3. Insert , Delete , data
string& 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++;
return *this;
}
string& insert(size_t pos, const char* str)
{
assert(pos <= _size);
size_t len = strlen(str);
if (_size + len > _capacity)
{
reserve(_size + len);
}
// Move back len A place
size_t end = _size + len;
while (end > pos+len-1)
{
_str[end] = _str[end -len];
--end;
}
strncpy(_str + pos, str, len);
_size += len;
return *this;
}
string& earse(size_t pos, size_t len = npos)//size_t nops=-1;
{
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;
}
return *this;
}
// Reuse
string& operator+=(const char* str)
{
append(str);
return *this;
}
string& operator+=(char ch)
{
push_back(ch);
return *this;
}
void push_back(char ch)
{
//if (_size == _capacity)
//{
// reserve(_capacity == 0 ? 4 : _capacity*2);
// //reserve(_capacity*2);
//}
//_str[_size] = ch;
//++_size;
//_str[_size] = '\0';
insert(_size, ch);
}
void append(const char* str)
{
/*size_t len = _size + strlen(str);
if (len > _capacity)
{
reserve(len);
}
strcpy(_str + _size, str);
_size = len;*/
insert(_size, str);//
}4. lookup
size_t find(char ch, size_t pos = 0)
{
for (; pos < _size; ++pos)
{
if (_str[pos] == ch)
{
return pos;
}
}
return npos;
}
size_t find(const char* str, size_t pos = 0)
{
const char* p = strstr(_str + pos, str);
if (p == nullptr)
{
return npos;
}
else
{
return p - _str;
}
}5. Operator overload
ostream& operator<<(ostream& out, const string& s)
{
for (auto ch : s)
{
out << ch;
}
return out;
}
istream& operator>>(istream& in, string& s)
{
char ch;
in >> ch;
ch = in.get();
while (ch != ' ' && ch != '\n')
{
s += ch;
in >> ch;
ch = in.get();
}
return in;
// Or reduce the cost of capacity expansion
char ch;
ch = in.get();
char buff[128] = {'\0'};
size_t i = 0;
while (ch != ' ' && ch != '\n')
{
buff[i++] = ch;
if (i == 127)
{
s += buff;
memset(buff, '\0', 128);
i = 0;
}
ch = in.get();
}
s += buff;
return in;
}
bool operator<(const string& s1, const string& s2)
{
return strcmp(s1.c_str(), s2.c_str()) < 0;
}
bool operator==(const string& s1, const string& s2)
{
return strcmp(s1.c_str(), s2.c_str()) == 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)
{
return !(s1 == s2);
}6. structure , copy constructor
Another way to do it
void swap(string& s)
{
std::swap(_str, s._str);
std::swap(_size, s._size);
std::swap(_capacity, s._capacity);
}
// s2(s1)
string(const string& s)
:_str(nullptr)
, _size(0)
, _capacity(0)
{
string tmp(s._str);
swap(tmp);
}
string& operator=(string s)// Value passed
{
swap(s);// Shape parameter s Change will not change s
return *this;
}边栏推荐
- Delegate parents and other loaders
- An error, uncaught typeerror: modalfactory is not a constructor
- function/symbol ‘pango_ context_ set_ round_ glyph_ positions‘ not found in library ‘libpango-1.0. so. 0‘x
- Basic operation of tree
- Docker安装MySQL
- TiDB 内存控制文档
- SQL union operator
- LeetCode 745. Prefix and suffix search
- 【多线程】JUC详解 (Callable接口、RenntrantLock、Semaphore、CountDownLatch) 、线程安全集合类面试题
- Stc8h development (XIV): I2C drive rx8025t high-precision real-time clock chip
猜你喜欢

机器人开发--常用仿真软件工具

委派双亲之类加载器

性能优化之@Contended减少伪共享

TCP congestion control details | 7 Surpass TCP

Docker install MySQL

How to change and reset forgotten root password in RHEL 9

学习笔记3--规划控制中的机器学习基本思想

【多线程】JUC详解 (Callable接口、RenntrantLock、Semaphore、CountDownLatch) 、线程安全集合类面试题

Sword finger offer II 041 Average value of sliding window

A fastandrobust volutionalneuralnetwork based defect detection model inproductqualitycontrol reading notes
随机推荐
Keras深度学习实战(14)——从零开始实现R-CNN目标检测
机器人开发--机器人资料汇总
03-1、内联函数、auto关键字、typeid、nullptr
Solve the problem that QQ mail and Thunderbird cannot log in to outlook
03-2、
Today's sleep quality record 79 points
解决邮件客户端QQ Mail及Thunderbird无法登入Outlook的问题
【二叉树】之力扣牛客必刷题
A simple output method of promise object to the result in nodejs (it is recommended to use the asynchronous ultimate scheme async+await)
TiKV 内存参数性能调优
A curated list of awesome Qt and QML
JVM hook hooks function
zabbix代理服务器配置
Robot development -- common simulation software tools
Stc8h development (XIV): I2C drive rx8025t high-precision real-time clock chip
Set the interface language of CMD command prompt window to English
Limit query of MySQL optimization series
华为无线设备配置频谱导航
【多线程】JUC详解 (Callable接口、RenntrantLock、Semaphore、CountDownLatch) 、线程安全集合类面试题
Leetcode 1328. 破坏回文串(可以,已解决)