当前位置:网站首页>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;
}边栏推荐
- To build agile teams, these methods are indispensable
- The basic establishment of the sequence table and the related operations of adding, deleting, modifying and querying (the sequence table described in C language)
- 下推计算结果缓存
- function/symbol ‘pango_ context_ set_ round_ glyph_ positions‘ not found in library ‘libpango-1.0. so. 0‘x
- jconsole线程面板中的阻塞总数和等待总数(转)
- Docker install MySQL
- Unity high version returned low version error
- Leetcode 1328. Destroy palindrome string (yes, solved)
- CodeForces - 587E(线性基+线段树+差分)
- Robot development -- common simulation software tools
猜你喜欢
![[PostgreSQL] PostgreSQL 15 optimizes distinct](/img/7c/89d05171902dd88bd2b5c352c3614f.png)
[PostgreSQL] PostgreSQL 15 optimizes distinct

Transport layer -------- TCP (I)

Total number of blocking and waiting in jconsole thread panel (RPM)

02 - 3. Différences entre les pointeurs et les références

466-82(3、146、215)

QT -- excellent open source project

Cv02 Roge matrix, rotation vector, angle

Send blocking, receive blocking

JVM hook hooks function
![[untitled] CV learning 1 conversion](/img/22/55d171f49659e704951ebd82a33f06.png)
[untitled] CV learning 1 conversion
随机推荐
Dream CMS Front Office Search SQL Injection
Sword finger offer II 041 Average value of sliding window
Leetcode 1252. Number of odd value cells
机器人开发--机器人资料汇总
Leetcode 1328. 破坏回文串(可以,已解决)
565. 数组嵌套 : 常规模拟题
Region 性能调优
To build agile teams, these methods are indispensable
QT two overloaded qlistwidget control objects implement selectitem drag drag
Will causal learning open the next generation of AI? Chapter 9 Yunji datacanvas officially released the open source project of ylarn causal learning
Daily question brushing record (26)
要想组建敏捷团队,这些方法不可少
OA系统与MES系统的异同点
Transport layer -------- TCP (I)
Dream CMS foreground search SQL injection
At5147-[agc036d]negative cycle [DP, model conversion]
CodeForces - 587E(线性基+线段树+差分)
The difference between CPU load and CPU utilization
Un modèle de détection par défaut basé sur le réseau neuronal évolutif rapide dans le contrôle de la qualité des produits - lire les notes
LeetCode刷题——查找和最小的 K 对数字#373#Medium