当前位置:网站首页>String class
String class
2022-07-27 05:18:00 【Cristiano777.】
One 、string Common interfaces of class objects
1.1 string Common constructs of class objects
| The name of the function | function |
| string() | Construct empty string Class object , Empty string |
string(const char* s) | use C Format string to construct string Class object |
string(size_t n, char c) | string Class objects contain n Characters c |
string(const string&s) | copy constructor |
int main()
{
string s1;// Construct empty string Class object s1
string s2("hello world");// use C Format string construction string Class object s2
string s3(s2);// Copy s2 structure s3
string s4 = s2;// Copy s2 structure s4, and s3 The effect is the same
string s5("hello world", 4);
//s5 take "hello world" front 4 individual , namely s5 = "hell"
string s6(10,'s');
//s6 take 10 individual s, namely s6 = "ssssssssss"
string s7(s2, 6, 3);
//s7 from s2 Of the 6 Start later 3 individual , namely s7 = "wor"
string s8(s2, 6, 200);
//s8 from s2 Of the 6 Start later 200 individual , If it is out of range, it ends at the end , namely s8 = "world"
string s9(s2, 6);
//s9 from s2 Of the 6 Start later , Until the end , namely s9 = "world"
cout << "s1:" << s1 << endl;
cout << "s2:" << s2 << endl;
cout << "s3:" << s3 << endl;
cout << "s4:" << s4 << endl;
cout << "s5:" << s5 << endl;
cout << "s6:" << s6 << endl;
cout << "s7:" << s7 << endl;
cout << "s8:" << s8 << endl;
cout << "s9:" << s9 << endl;
return 0;
}
1.2 string Class object capacity operation
| The name of the function | function |
| size | Returns the valid character length of a string |
| length | Returns the valid character length of a string |
| capacity | Return the total size of the space |
| empty | Detection string released as empty string , Is to return true, Otherwise return to false |
| clear | Empty valid characters |
| reserve | Reserve space for Strings ** |
| resize | The number of valid characters should be n individual , Extra space with characters c fill |
int main()
{
//string Class objects support cin and cout Input 、 Output
string s1("hello world");
string s2;
string s3 = "hello world";
string s4 = s3;
string s5 = s3;
// You can assign values directly
s2 = "hello world";
cout << s1.size() << endl;
cout << s1.length() << endl;
cout << s1.capacity() << endl;
cout << s1.empty() << endl;
//clear Empty string , the size clear 0, But do not change the underlying space (capacity)
s1.clear();
cout << s1 << endl;
cout << s1.size() << endl;// Clear as 0
cout << s1.capacity() << endl;// unchanged
//resize take s2 Number of valid characters (size) become 20 individual , For extra positions 'c' Fill in
s2.resize(20, 'c');
//s2: "hello world" -> "hello worldccccccccc"
cout << s2 << endl;
cout << s2.size() << endl;// 11 -> 20
//resize take s3 Number of valid characters (size) become 20 individual , For extra positions '\0' Fill in
s3.resize(20);
//s3: "hello world" -> "hello world\0\0\0\0\0\0\0\0\0"
cout << s3 << endl;
cout << s3.size() << endl;// 11 -> 20
//resize take s4 Number of valid characters (size) become 5 individual
s4.resize(5);
//s4: "hello world" -> "hello"
cout << s4 << endl;
cout << s3.size() << endl;// 11 -> 5
//reverse Will not change string Number of valid elements in the (size)
//reserve The parameter is less than string Bottom space (capacity) Big hour , Space will not shrink
s5.reserve(5);
cout << s5.size() << endl;
cout << s5.capacity() << endl;
//reserve Parameter is greater than the string Bottom space (capacity) Big hour , Space will expand
s5.reserve(100);
cout << s5.size() << endl;
cout << s5.capacity() << endl;
return 0;
}Be careful :
- size() And length() The underlying implementation principle of the method is exactly the same , introduce size() The reason for this is to be consistent with the interfaces of other containers , In general, it's basically used size().
- clear() Just to string Empty the valid characters in the , Don't change the size of the underlying space .
- resize(size_t n) And resize(size_t n, char c) All are to change the number of valid characters in the string to n individual , The difference is When the number of characters increases :resize(n) use '\0' To fill in the extra element space ,resize(size_t n, char c) Use characters c To fill in the extra element space . Be careful :resize When you change the number of elements , If you increase the number of elements , It may change the size of the underlying capacity , If it is to reduce the number of elements , The total size of the underlying space remains unchanged .
- reserve(size_t res_arg=0): by string Reserve space , Do not change the number of effective elements , When reserve The parameter of is less than string The total size of the ground floor is ,reserver It doesn't change the size of the capacity .
- reserve Is to expand space ,resize Is to expand space + initialization
- VS Next ,reserve and resize Will not shrink Capacity (capacity)
1.3 string Class object access and traversal operation
int main()
{
// Traverse s1 Every character of
string s1("hello world");
string s2 = "xxxxxx";
// The first way : Subscript +[]
for (size_t i = 0; i < s1.size(); i++)
{
cout << s1[i] << " ";
}
cout << endl;
// The second way : iterator ( It's something like a pointer )
string::iterator it = s1.begin();
while (it != s1.end())
{
cout << *it << " ";
++it;
}
cout << endl;
// The third way : Range for , principle : The system automatically replaces it with an iterator
for (auto ch : s1)
{
cout << ch << " ";
}
cout << endl;
// access , and C almost
s1[0];// 'h'
s1[0] = 'c';// 'h' -> 'c'
// Iterators are also divided into forward and reverse
// Forward iterator , Before and after
string::iterator it = s1.begin();
while (it != s1.end())
{
(*it) += 1;// You can modify the string content
cout << *it << endl;
it++;
}
cout << endl;
// reverse iterator , From back to front
string::reverse_iterator rit = s1.rbegin();
while (rit != s1.rend())
{
(*rit) += 1;
cout << *rit << endl;
rit++;
}
cout << endl;
s1.swap(s2);// Efficient , Exchange of pointer
swap(s1, s2);// Low efficiency , Deep copy
return 0;
}1.4 string Class object modification operation
| The name of the function | function |
push_back | Insert after the string character c( It's not a string ) |
append | Append a string to the string |
operator+= | Append the string after the string str |
c_str | return C Format string |
rfind | From a string pos The position begins to look forward for characters c, Returns the position of the character in the string |
substr | stay str In the from pos Position start , Intercept n Characters , Then return it to |
int main()
{
string s1("hello world");
s1.push_back('!');// stay s1 Insert... At the back '!'
s1.append("!!");// stay s1 Insert... At the back "!!"
s1 += '!';// stay s1 Insert... At the back '!'
s1 += "!!";// stay s1 Insert... At the back "!!"
cout << s1 << endl;
cout << s1.c_str() << endl;// With C Language format print string
// Read test.cpp The suffix
string s2("test.cpp");
size_t pos = s2.rfind('.');
//find It's from the past to the future
//rfind It's back to front
string s(s2.substr(pos, s2.size() - pos));
//substr:
// stay s2 In the from pos Position start , Intercept [s2.size()-pos] Characters , Then return it to
cout << s << endl;
return 0;
}Two 、string Class simulation implementation
2.1 Achieve one string, Only consider the deep and shallow copy of resource management , For the time being, we will not consider adding, deleting, checking and modifying
// Deep copy
namespace Cris
{
class string
{
public:
string(const char* str)
:_str(new char[strlen(str)+1])
{
strcpy(_str, str);
}
string(const string& s)
:_str(new char[strlen(s._str)+1])
{
strcpy(_str, s._str);
}
string& operator=(const string& s)
{
if (this != &s)
{
char* tmp = new char[strlen(s._str) + 1];
strcpy(tmp, s._str);
delete[] _str;
_str = tmp;
}
return *this;
}
private:
char* _str;
};
}2.2 string Class simulation implementation
namespace Cris
{
class string
{
public:
// All default
string(const char* str = "")
:_size(strlen(str))
, _capacity(_size)
{
_str = new char[_capacity + 1];
strcpy(_str, str);
}
string(const string& s)
:_size(strlen(s._str))
, _capacity(_size)
{
_str = new char[_capacity + 1];
strcpy(_str, s._str);
}
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()
{
if (_str)
{
delete[] _str;
_str = nullptr;
_size = _capacity = 0;
}
}
const char* c_str() const
{
return _str;
}
char& operator[](size_t pos)
{
assert(pos < _size);
return _str[pos];
}
const char& operator[](size_t pos) const
{
assert(pos < _size);
return _str[pos];
}
size_t size() const
{
return _size;
}
size_t capacity() const
{
return _capacity;
}
string& operator+=(const char* str)
{
append(str);
return *this;
}
string& operator+=(char ch)
{
push_back(ch);
return *this;
}
void reserve(size_t n)
{
if (n > _capacity)
{
char* tmp = new char[n + 1];
strcpy(tmp, _str);
delete[] _str;
_str = tmp;
_capacity = n;
}
}
// Expand space + initialization
// Delete some data , Leave the n individual
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';
}
}
void push_back(char ch)
{
/*if (_size == _capacity)
{
reserve(_capacity == 0 ? 4 : _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);
//}
_str Is the first address of the string
_str + _size Is the end of string address
//strcpy(_str + _size, str);
//_size = len;
insert(_size, str);
}
// Insert characters
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;
}
// Insert string
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& 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;
}
return *this;
}
// Find the character in the string
size_t find(char ch, size_t pos = 0)
{
for (; pos < _size; pos++)
{
if (_str[pos] = ch)
return pos;
}
return npos;
}
// Find the string in the string
size_t find(const char* str, size_t pos = 0)
{
//strstr: In string _str+pos Find string in str
const char* p = strstr(_str + pos, str);
if (p == nullptr)
{
return npos;
}
else
{
return p - _str;
}
}
private:
char* _str;
size_t _size;// Number of valid characters
size_t _capacity;// The actual space to store valid characters
const static size_t npos;
};
}
const size_t string::npos = -1;
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;
char ch;
ch = in.get();
char buff[128] = { '\0' };
size_t i = 0;
// full 128 Put them in once , Increase of efficiency
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);
}
边栏推荐
- Introduction to Kali system ARP (network disconnection sniffing password packet capturing)
- How idea creates a groovy project (explain in detail with pictures and texts)
- Use ngrok for intranet penetration
- 牛客剑指offer--JZ12 矩阵中的路径
- Dialog introduction
- Mysql表的约束
- idea远程调试debug
- Solution to Dlib installation failure
- TypeScript 详解
- Introduction to Web Framework
猜你喜欢

Installation and template setting of integrated development environment pychar

Read write separation and master-slave synchronization

JVM上篇:内存与垃圾回收篇十四--垃圾回收器

Could not autowire. No beans of ‘userMapper‘ type found.

Scientific Computing Library -- Matplotlib

Bean的生命周期&&依赖注入*依赖自动装配

2、 MySQL advanced

事件(event)

树莓派rtmp推流本地摄像头图像

Standard dialog qmessagebox
随机推荐
Differences among left join, inner join and right join
JVM Part 1: memory and garbage collection part 7 -- runtime data area heap
B1025 反转链表*******
MQ message queue is used to design the high concurrency of the order placing process, the generation scenarios and solutions of message squeeze, message loss and message repetition
Why is count (*) slow
Event filter
Detailed description of polymorphism
JVM上篇:内存与垃圾回收篇七--运行时数据区-堆
DBUtils
Bean的生命周期&&依赖注入*依赖自动装配
Three paradigms, constraints, some keyword differences,
feign调用丢失请求头问题解决及原理分析
Typescript details
探寻通用奥特能平台安全、智能、性能的奥秘!
Use ngrok for intranet penetration
使用Druid连接池创建DataSource(数据源)
Slashes / and backslashes involved in writing code\
辗转相除法
Use of file i/o in C
对话框数据传递