当前位置:网站首页>Understand the string class
Understand the string class
2022-07-26 11:57:00 【Hundred words lingdu】
string
understand string
string Is a class that represents character sequences
string Class is basic_string An instance of the template class , It USES char To instantiate basic_string Template class .
string At the bottom, it's actually :basic_string Alias of template class ,
typedef basic_string<char> string;
- string class management Dynamic growth The characters of Array , This string takes
\0ending , Array Stored in the heap .
string Common constructions of class objects
The name of the function Functional specifications string() Construct empty string Class object , Empty string string(const char s)* use C 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 string (const string& str, size_t pos, size_t len = npos) Copy str The subscript of is pos The position begins ,len Character construction string (const char s, size_t n)* Constructors ,C Before string n Characters void test1() { char a[10] = "qwer"; string s1; // Construct empty string Class object s1 string s2(a); // use C Format string construction string Class object s2 string s3("hello world");// Construct with constant string string Class object s3 string s4(s2); // Copy structure s4 string s5(5, 'x');// structure string Class objects contain n Characters c string s6(s3,6,3);// Copy s3 The subscript of is 6 The position begins , Three character construction s6 string s7(s3,6,100);// Over length , Take as many as you can string s8(s3,6);// take npos Characters ,static const size_t npos = -1; string s9("1234567890",4);// structure s9,C The first four characters of the string }Be careful :
- **
string (const string& str, size_t pos, size_t len = npos)Is semi default ,static const size_t npos = -1, Iflen** Over length , Take as many as you can
string Class assignment overloaded function
string s1("hello"); string s2("xxx"); s1=s2; //string Class can be assigned s1="qwer"; //C Strings can be assigned s1='q'; // A single character can be assigned
string Class object capacity operation
The name of the function Functional specifications 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 ( Change capacity ) resize Change the number of valid characters to n individual , Extra space with characters c fill ( Will the initialization ('\0’ Or specify characters )+ Change capacity ) void test() { string s1("hello world"); cout << s1 << endl; cout << "capacity:" << s1.capacity() << endl; cout << "size:" << s1.size() << endl; cout << "lenth:" << s1.length() << endl; s1.resize(40, 'x'); cout << "after resize capacity:" << s1.capacity() << endl; cout << "after resize size:" << s1.size() << endl; s1.reserve(50); cout << "after reserve capacity:" << s1.capacity() << endl; cout << "after reserve size:" << s1.size() << endl; s1.clear(); cout << "empty:" << s1.empty() << endl; cout << "after clear capacity:" << s1.capacity() << endl; cout << "after clear size:" << s1.size() << endl; }
Be careful :
- size() And length() The underlying implementation principle of the method is exactly the same , introduce size() The reason for this is to keep an interface with other containers Cause , In general It's basically using 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 that 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 ( When the number of elements increases , If the capacity is not enough , Expand the underlying capacity , If the capacity is enough , The underlying capacity remains unchanged ), 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 Parameters of Less than string The total size of the ground floor is ,reserver It doesn't change the size of the capacity .
string Class object access and traversal operation
string There are three ways to traverse class objects
Subscript + []
operator[]
for(size_t i=0;i<s1.size();i++) { //s1.operator[](i) cout<<s1[i]<<""; }operator[] Function explanation
1、char& operator[] (size_t pos); 2、const char& operator[] (size_t pos) const; The return value is the reference , To modify , If it is a value, return , Return the intermediate variable , Intermediate variables have constant properties , Do not modify theiterator
Concept : Iterators are things like pointers , Or pointers are used to access data structures .
Get iterator function
begin():begin Get an iterator of a character
end():end Gets the iterator at the next position of the last character
rbegin:rbegin Get the iterator of the last character
rend:rend Gets the iterator that precedes the first characterFour iterators
Forward iterator ( Can read but write )
string s1("Hello World"); string::iterator it = s1.begin(); while(it!=s1.end()) { cout<<*it<<" "; ++it; } cout<<endl;reverse iterator ( Can read but write )
string::reverse_iterator rit = s1.rbegin(); while(rit!=s1.rend()) { cout<<*rit<<" "; ++rit; } cout<<endl;Forward iterator ( read-only )
string::const_iterator it = s1.begin(); while(it!=s1.end()) { cout<<*it<<" "; ++it; } cout<<endl;reverse iterator ( read-only )
string::const_reverse_iterator rit = s1.begin(); while(rit!=s1.end()) { cout<<*rit<<" "; ++rit; } cout<<endl;Range for
for(auto ch:s1) { cout<<ch<<" "; ++it; } cout<<endl;
Add :
[]
Transboundary : Assertion processing
at
Transboundary : Throw exception handling
string Class object modification operation
The name of the function Functional specifications push_back At the end of a string c( insert data , If the capacity is not enough , It will expand ( Probably 1.5 times )) append Append a string to the string operator+=( The most commonly used ) Append the string after the string str c_str return C Format string ( Return to point str The pointer ) find From a string pos The position begins to look for the character back c, Returns the position of the character in the 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 Function declaration :
//push_back void push_back (char c); //c_str const char* c_str() const; //find size_t find (const string& str, size_t pos = 0) const; size_t find (const char* s, size_t pos = 0) const; size_t find (char c, size_t pos = 0) const; //rfind size_t rfind (const string& str, size_t pos = npos) const; size_t rfind (const char* s, size_t pos = npos) const; size_t rfind (char c, size_t pos = npos) const; //substr string substr (size_t pos = 0, size_t len = npos) const;void Teststring() { string str; str.push_back(' '); // stay str Insert space after str.append("hello"); // stay str Add a character after "hello" str += 'w'; // stay str Add a character after 'b' str += "orld"; // stay str Append a string after "it" cout << str << endl; cout << str.c_str() << endl; // With C Print the string in the way of language // obtain file The suffix string file1("string.cpp"); size_t pos = file1.rfind('.'); string suffix(file1.substr(pos, file1.size() - pos)); cout << suffix << endl; // npos yes string A static member variable inside // static const size_t npos = -1; }
extract url The agreement in domain name uri
string url1("http://www.cplusplus.com/reference/string/string/find/"); string& url = url1; // Take out url The agreement in string protocol; size_t pos1 = url.find("://"); if (pos1 != string::npos) { protocol = url.substr(0, pos1); cout << "protocol:" << protocol << endl; } else { cout << " illegal url" << endl; } // Take out url The domain name string domain; size_t pos2 = url.find('/', pos1 + 3); if (pos2 != string::npos) { domain = url.substr(pos1 + 3, pos2 - (pos1 + 3)); cout << "domain:" << domain << endl; } else { cout << " illegal url" << endl; } // Take out url Medium uri string uri = url.substr(pos2 + 1); cout << "uri:" << uri << endl;
insert
Function declaration :
string& insert (size_t pos, size_t n, char c); iterator insert (iterator p, char c);void test() { string s("hello world"); s.insert(0, 1, 'x'); cout << s << endl; s.insert(s.begin(), 'y'); cout << s << endl; s.insert(3, 1, 'x'); cout << s << endl; s.insert(s.begin() + 3, 'y'); cout << s << endl; }
erase
Function declaration :
string& erase (size_t pos = 0, size_t len = npos); iterator erase (iterator p);void test() { string s("hello world"); s.erase(s.begin()); cout << s << endl; string s1("hello world"); s1.erase(s1.begin() + 3); cout << s1 << endl; string s2("hello world"); s2.erase(3, 2); cout << s2 << endl; string s3("hello world"); s3.erase(3); cout << s3 << endl; //lenth The default value (-1), End of deletion }
swap(string Within class )
Function declaration :
void swap (string& str);void test() { string s1("hello world"); string s2("string"); s1.swap(s1);// Efficient ( Exchange of pointer ) swap(s1,s2);// Low efficiency ( Deep copy ) }Be careful :
string In class swap Function is by exchanging pointers to dynamic arrays , Realize exchange **( Efficient )**
std::swapFunction is to realize exchange through deep copy **( Low efficiency )**
边栏推荐
- 7月27日19:30直播预告:HarmonyOS3及华为全场景新品发布会
- 什么是Per-Title编码?
- Esp8266 Arduino programming example - development environment construction (based on platformio)
- 程序员培训学习后好找工作吗?
- 零基础小白也能懂的 Redis 数据库,手把手教你易学易用!
- Database composition storage engine
- 种种迹象表明,Apple将有望支持AV1
- System call capture and analysis conclusion making system call log collection system
- 【通信原理】第三章 -- 随机过程[上]
- 数据库组成存储引擎
猜你喜欢

Substance painter 2021 software installation package download and installation tutorial

Audio and video+

An online duplicate of a hidden bug

Pytorch——基于mmseg/mmdet训练报错:RuntimeError: Expected to have finished reduction in the prior iteration

3.1 创建菜单与游戏页面——上

Hou Peixin, chairman of the openharmony Working Committee of the open atom open source foundation, sent a message to the openatom openharmony sub forum

。。。。。。

Metauniverse gamefi chain game system development NFT Technology

专访即构科技李凯:音视频的有趣、行业前沿一直吸引着我

系统调用捕获和分—Ring3层LD_PRELOAD机制进行库函数劫持
随机推荐
Win10 uses NVM to install node, NPM, and cnpm
Redis database, which can be understood by zero foundation Xiaobai, is easy to learn and use!
【通信原理】第二章 -- 确知信号
【通信原理】第一章 -- 绪论
【通信原理】第三章 -- 随机过程[上]
4.1 configure MySQL and register login module
线上一个隐匿 Bug 的复盘
Metauniverse gamefi chain game system development NFT Technology
PostgreSQL在Linux和Windows安装和入门基础教程
系统调用捕获和分析完结篇制作系统调用日志收集系统
[cloud co creation] what good habits do you adhere to in order to write good code?
[cloud resident co creation] decrypt how sparkrtc realizes ultra-low latency interaction globally
Acwing727. Diamond pattern
System call capture and analysis - ring layer kprobe hijacks system calls
Data center construction (II): brief introduction to data center
10 reduce common "tricks"
PostgreSQL in Linux and windows installation and introductory basic tutorial
Subject 3 turns and turns
Li Kai: the interesting and cutting-edge audio and video industry has always attracted me
Substance painter 2021 software installation package download and installation tutorial






