当前位置:网站首页>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 )**
边栏推荐
- 4.1 configure MySQL and register login module
- Swagger2.9.2 tutorial and swagger3.0.0 tutorial
- PostgreSQL in Linux and windows installation and introductory basic tutorial
- 元宇宙日报|元宇宙社交 App“派对岛”产品下架;广州南沙元宇宙产业集聚区揭牌;数字经济发展部际联席会议制度推出
- c语言代码量统计工具
- MILA旗下初创企业Ubenwa获得250万美元投资,研究婴儿健康AI诊断
- Exploration on cache design optimization of community like business
- Some practical, commonly used and increasingly efficient kubernetes aliases
- Meiker Studio - Huawei 14 day Hongmeng equipment development practical notes 8
- Hou Peixin, chairman of the openharmony Working Committee of the open atom open source foundation, sent a message to the openatom openharmony sub forum
猜你喜欢

初试YOLOv7

Esp8266 Arduino programming example - development environment construction (based on platformio)

了解 useRef 一篇就够了

Server memory failure prediction can actually do this!

如何使用数据管道实现测试现代化

Metauniverse gamefi chain game system development NFT Technology

System call capture and segmentation - RING3 layer LD_ Preload mechanism for library function hijacking

PostgreSQL in Linux and windows installation and introductory basic tutorial

Li Kai: the interesting and cutting-edge audio and video industry has always attracted me

7月27日19:30直播预告:HarmonyOS3及华为全场景新品发布会
随机推荐
System call capture and analysis - ring layer kprobe hijacks system calls
There are various signs that apple is expected to support AV1
Application scheme of ankerui residual pressure monitoring system in residential quarter
Pycharm is really strong
MICCAI2022论文 | 进化多目标架构搜索框架:在COVID-19三维CT分类中的应用
虚拟偶像代言产品出问题谁负责? 且听律师分析
Pyechart offline deployment
pytest接口自动化测试框架 | pytest配置文件
Practice of microservice in solving Library Download business problems
元宇宙GameFi链游系统开发NFT技术
向日葵远程控制为何采用BGP服务器?自动最优路线、跨运营商高速传输
国内11所“袖珍”大学!在校园跑步,还没加速就出校门了...
X 2 earn must rely on Ponzi startup? Where is the way out for gamefi? (top)
了解 useRef 一篇就够了
Question and answer No. 48: geek appointment - construction path of observable system
Sunflower senior product director technology sharing: how to apply in AD domain environment
数据库组成 触发器
Didi was fined 8billion! The era of making money from user data is over
The latest heart-shaped puzzle applet source code + with flow master
Hashtable






