行业知识
【C++】string进一步介绍
2026-11-28 16:49:34
来源:互联网转载
个人主页 : zxctscl
如���转载请先通知
文章目录
- 1. 前言
- 2. 迭代器
- 2.1 反向迭代器
- 2.2 const对象迭代器
- 3. Capacity
- 3.1 size和length
- 3.2 max_size
- 3.3 capacity
- 3.4 clear
- 3.5 shrink_to_fit (了解即可)
- 3.6 reserve
- 3.7 resize
- 4. Element access
- 4.1 operator[]
- 4.2 at
- 5. Modifiers
- 5.1 push_back
- 5.2 append
- 5.3 operator+=
- 5.4 assign(了解即可)
- 5.5 insert
- 5.6 erase
- 5.7 replace
- 5.8 swap
- 6. String operations
- 6.1 c_str
- 6.2 find 和 substr
- 6.3 rfind
- 6.4 compare
- 7. Non-member function overloads
- 7.1 operator+
- 7.2 getline
1. 前言
在之前的博客中初步介绍了string一下: 【C++】string类初步介绍,那么这次来看看它的实现。
2. 迭代器
string类对象的访问及遍历操作:
函数名称 功能说明 operator[] (重点) 返回pos位置的字符,const string类对象调用 begin+ end begin获取一个字符的迭代器 + end获取最后一个字符下一个位置的迭代器 范围for C++11支持更简洁的范围for的新遍历方式 rbegin + rend rbegin反向迭代器以反向开始,end将迭代器返回到末尾 2.1 反向迭代器
在前面的一篇中已经提到了前面三个,这次来看看反向迭代器。
reverse_iterator:将给的字符串反向逆置。
void test_string3(){string s1("hello,world");string::reverse_iterator rit = s1.rbegin();while (rit != s1.rend()){cout *it2 += 3;cout cout string s1("hello world");cout s.push_back('c');if (sz != s.capacity()){sz = s.capacity();cout s.push_back('c');if (sz != s.capacity()){sz = s.capacity();cout string s1("hello world");s1.push_back('!');cout s2.replace(pos, 1, "%20");pos = s2.find(' ');}cout if (ch != ' '){s3 += ch;}else{s3 += "%20";}}cout string s2("hello world hello abcd");string s3;s3.reserve(s2.size());for (auto ch : s2){if (ch != ' '){s3 += ch;}else{s3 += "20%";}}cout string s1("hello world");string filename("test.cpp");FILE* fout = fopen(filename.c_str(), "r");}string s1("file.cpp");size_t pos1= s1.find('.');if (pos1 != string::npos){string suffix = s1.substr(pos1);cout cout string s1("file.cpp.tar.zip");size_t pos1= s1.rfind('.');if (pos1 != string::npos){string suffix = s1.substr(pos1);cout cout string url1("https://legacy.cplusplus.com/reference/string/string/substr/");string protocol, domain, uri;//协议,域名,网址size_t i1 = url1.find(':');if (i1 != string::npos){protocol = url1.substr(0, i1 - 0);cout domain = url1.substr(i1+3, i2-(i1+3));cout string line;// 不要使用cinline,因为会它遇到空格就结束了// while(cinline)while (getline(cin, line)){size_t pos = line.rfind(' ');cout
上一篇:战机世界怎么改服务器?
下一篇:怎么安装dell服务器cpu?