One 、string Concept

string yes STL String type of , Usually used to represent strings . But in the use of string Before , A string is usually written with char* It means .string And char* Can be used to represent strings , So what's the difference between them .

string and char* Comparison :

  • string Is a class , char* It's a pointer to a character .

    ​ string Encapsulates the char*, Manage this string , It's a char* A new type of container .

  • string Don't worry about memory release and out of bounds .

    ​ string management char* Allocated memory . every time string Copy , All values are determined by string Class is responsible for maintaining , You don't have to worry about copying and value crossing .

  • string Provides a series of string manipulation functions

    ​ lookup find, Copy copy, Delete erase, Replace replace, Insert insert

//string  turn  char*
string str_1="string";
const char* cstr_1=str.c_str();
//char* turn string
char* cstr_2="char";
string str_2(cstr);

Two 、string Constructor for

  1. Default constructor :string(); // Construct an empty string string s1.

  2. Constructors :string(const string &str); // Construct a relationship with str Same string. Such as string s1(s2).

  3. Constructor with parameters :

    string(const char *s); // Use string s initialization

    string(int n,char c); // use n Characters c initialization

	string s1; // Call parameterless construction 
string s2(10, 'a');
string s3("abcdefg");
string s4(s3); // Copy structure cout << s1 << endl;
cout << s2 << endl;
cout << s3 << endl;
cout << s4 << endl;
/*
result : aaaaaaaaaa
abcdefg
abcdefg
*/

3、 ... and 、string Access character operations for

string Class :

  • const char &operator[] (int n) const; // adopt [] The way to get characters
  • const char &at(int n) const; // adopt at Method to get the character
  • char &operator[] (int n);
  • char &at(int n);

operator[] and at() Returns the second... In the current string n Characters , But they are different .

The main difference is that at() An exception will be thrown when the boundary is crossed ,[] It will return when it just crosses the boundary (char)0, When we continue to cross the border , Compiler error directly . If your program wants to go through try,catch Capture exception , The proposal USES at().

	string s1 = "abcdefg";

	// heavy load [] The operator 
for (int i = 0; i < s1.size(); i++) {
cout << s1[i] << " ";
}
cout << endl; //at Member functions
for (int i = 0; i < s1.size(); i++) {
cout << s1.at(i) << " ";
}
cout << endl; // difference :[] The way If the visit goes beyond the boundary , Just hang up
//at The way Cross border visit Throw exceptions out_of_range try {
//cout << s1[100] << endl;
cout << s1.at(100) << endl;
}
catch (...) {
cout << " Transboundary !" << endl;
}
/*
result :
a b c d e f g
a b c d e f g
Transboundary !
*/

Four 、 from string obtain const char* The operation of

const char *c_str() const; // Return one to '\0' The first address of the ending string

//string  turn  char*
string str_1="string";
const char *cstr_1=str.c_str();

5、 ... and 、 hold string copy to char* Point to the memory space of the operation

int copy(char *s, int n, int pos=0) const;

Put the current string with pos At the beginning n Copy characters to s Is the starting position of the character array , Returns the actual number of copies . Make sure s The space pointed to is large enough to hold the current string , Or you'll cross the line .

	string s1 = "abcdefg";
int n = 5;pose
int pose = 3; char* s2 = (char*)malloc(n*sizeof(char));
if(s1.copy(s2, n, pose))
cout << s2 ;
else cout<<"error"<<endl;
/*
result :
def
*/

6、 ... and 、string The length of

int length() const; // Returns the length of the current string . The length does not include the end of the string '\0'.

bool empty() const; // Whether the current string is empty

	string s1 = "abcdefg";
string s2 = ""; int s1_length=s1.length();
bool s1_empty = s1.empty();
int s2_length = s2.length();
bool s2_empty = s2.empty(); cout << s1_length << " " << s1_empty << endl;
cout << s2_length << " " << s2_empty << endl;
/*
result :
7 0
0 1
*/

7、 ... and 、string Assignment

string &operator=(const string &s);// Put the string s Assign to the current string

string &assign(const char *s); // Put the string s Assign to the current string

string &assign(const char *s, int n); // Put the string s Before n Characters are assigned to the current string

string &assign(const string &s); // Put the string s Assign to the current string

string &assign(int n,char c); // use n Characters c Assign to the current string

string &assign(const string &s,int start, int n); // Put the string s In the from start At the beginning n Characters assigned to the current string

	string s1;
string s2("appp");
s1 = "abcdef";
cout << s1 << endl;
s1 = s2;
cout << s1 << endl;
s1 = 'a';
cout << s1 << endl; // Member method assign
s1.assign("jkl");
cout << s1 << endl;
/*
result :
abcdef
appp
a
jkl
*/

8、 ... and 、string String connection

string &operator+=(const string &s); // Put the string s Connect to the end of the current string

string &operator+=(const char *s);// Put the string s Connect to the end of the current string

string &append(const char *s); // Put the string s Connect to the end of the current string

string &append(const char *s,int n); // Put the string s Before n Characters connected to the end of the current string

string &append(const string &s); // Same as operator+=()

string &append(const string &s,int pos, int n);// Put the string s In the from pos At the beginning n Characters connected to the end of the current string

string &append(int n, char c); // Add... To the end of the current string n Characters c

	string s = "abcd";
string s2 = "1111";
s += "abcd";
s += s2;
cout << s << endl; string s3 = "2222";
s2.append(s3);
cout << s2 << endl; string s4 = s2 + s3;
cout << s4 << endl;
/*
result :
abcdabcd1111
11112222
111122222222
*/

Nine 、string Comparison

int compare(const string &s) const; // And string s Compare

int compare(const char *s) const; // And string s Compare

compare Function in > When to return to 1,< When to return to -1,== When to return to 0. Compare case sensitivity , Refer to dictionary order when comparing , The smaller the front row is . uppercase A It's smaller than lowercase a Small .

	string s1 = "abcd";
string s2 = "abce";
if (s1.compare(s2)==0) {
cout << " String equality !" << endl;
}
else {
cout << " Strings are not equal !" << endl;
}

Ten 、string The string of

string substr(int pos=0, int n=npos) const; // Return from pos At the beginning n A substring of characters

	string s = "abcdefg";
string mysubstr = s.substr(1, 3);
cout << mysubstr << endl;
/*
result :
bcd
*/

11、 ... and 、string Find and replace

lookup

int find(char c,int pos=0) const; // from pos Start finding characters c In the current string position

int find(const char *s, int pos=0) const; // from pos Start looking up strings s In the current string position

int find(const string &s, int pos=0) const; // from pos Start looking up strings s Position in the current string

//find If the function cannot be found , Just go back to -1

int rfind(char c, int pos=npos) const; // from pos Start looking for characters from back to front c Position in the current string

int rfind(const char *s, int pos=npos) const;

int rfind(const string &s, int pos=npos) const;

//rfind It means reverse search , If you can't find , return -1

Replace

string &replace(int pos, int n, const char *s);// Remove from pos At the beginning n Characters , And then in pos Insert string at s

string &replace(int pos, int n, const string &s); // Remove from pos At the beginning n Characters , And then in pos Insert string at s

void swap(string &s2); // Exchange the current string with s2 Value

	//  String search and replacement 
string s1 = "wbm hello wbm 111 wbm 222 wbm 333";
size_t index = s1.find("wbm", 0);
cout << "index: " << index; // seek itcast Number of occurrences
size_t offindex = s1.find("wbm", 0);
while (offindex != string::npos){ cout << " In subscript index: " << offindex << " find wbm\n";
offindex = offindex + 1;
offindex = s1.find("wbm", offindex);
} // Replace
string s2 = "wbm hello wbm 111 wbm 222 wbm 333";
s2.replace(0, 3, "wbm");
cout << s2 << endl; // seek itcast Number of occurrences
offindex = s2.find("wbm", 0);
while (offindex != string::npos){ cout << " In subscript index: " << offindex << " find wbm\n";
s2.replace(offindex, 3, "WBM");
offindex = offindex + 1;
offindex = s1.find("wbm", offindex);
}
cout << " Replace later s2:" << s2 << endl;
/*
result :
index: 0 In subscript index: 0 find wbm
In subscript index: 10 find wbm
In subscript index: 18 find wbm
In subscript index: 26 find wbm
wbm hello wbm 111 wbm 222 wbm 333
In subscript index: 0 find wbm
In subscript index: 10 find wbm
In subscript index: 18 find wbm
In subscript index: 26 find wbm
Replace later s2:WBM hello WBM 111 WBM 222 WBM 333
*/

Twelve 、String Interval deletion and insertion of

string &insert(int pos, const char *s);

string &insert(int pos, const string &s);// stay pos Position insert string s

string &insert(int pos, int n, char c); // stay pos Location Insert n Characters c

string &erase(int pos=0, int n=npos); // Delete pos At the beginning n Characters , Return the modified string

	string s = "abcdefg";
s.insert(3, "111");
cout << s << endl; s.erase(0, 2);
cout << s << endl;
/*
result :
abc111defg
c111defg
*/

STL_string More articles on containers

  1. docker—— erection of tank tomcat

    Write it at the front : continue docker Learning from , To study the docker After the basic common commands of , I am here docker Installation on jdk,tomcat Two basic java web Tools , Here is a record of the operation process . Software preparation : 1.jdk-7 ...

  2. Submit the web page in Chinese to WEB What's going through in the development of containers ....

    Prepare a web page first <html><meta http-equiv="Content-Type" content="text/html; charset=gb ...

  3. [Spring]IoC Comments on the attack of the container

    Let's start with a few words : For the first time in the blog Garden markdown edit , I feel that the rendering style is not satisfactory , still github The style is more pleasing to the eye . summary Spring2.5 The introduction of annotations . therefore , A problem arises : Use annotation to inject JavaB ...

  4. In depth understanding of DIP、IoC、DI as well as IoC Containers

    Abstract Object oriented design (OOD) Help us develop high performance . Easy to expand and reuse programs . among ,OOD There is an important thought that is to rely on the principle of inversion (DIP), And from this, it can be concluded that IoC.DI as well as Ioc Concept of container, etc . Through this article we will learn ...

  5. Docker Note 1 : be based on Docker The container builds and runs nginx + php + mysql ( mariadb ) Service environment

    First of all, why write your own Dockerfile To build  nginx.php.mariadb These three mirrors ? First, we hope to have a deeper understanding of Dockerfile Use , So we can have a preliminary understanding of docker How the image is constructed : Second, hope for the future ...

  6. JS The method and analysis of judging the direction of mouse entering the container window.open The problem of new windows being blocked

    1. Determine the direction of the mouse into the container It is a common problem to judge which direction the mouse enters the element container from , How to judge ? The first thing that comes to mind : Get the mouse position , And then through a lot of if..else Logic to determine . It's rather cumbersome , Here are two kinds of ...

  7. docker4dotnet #2 Containerized hosts

    .NET Since the ape met the little whale , I feel that my skill has been greatly improved . Part 1 <docker4dotnet #1 All men are mortal & Hello world > This article introduces how to use the Windows The above configuration Docker for Window ...

  8. In depth analysis Spring And Spring MVC Containers

    1 Spring MVC WEB To configure Spring Framework There is no such thing as Web function ,Spring MVC Use WebApplicationContext Class extensions ApplicationContext, ...

  9. Set Containers --HashSet aggregate

    Set Container features : ①   Set A container is one that does not contain duplicate elements Collection, And it contains at most one null Elements , It and List On the contrary ,Set A container cannot guarantee the order of its elements ; ②   The two most commonly used Set The implementation of the interface ...

  10. In depth understanding of Spring-- Make a simple SpringIOC Containers

    Contact Spring Nearly half a year , I just used it some time ago Spring4+S2H4 I finished my homework , But it obviously feels right Spring In especial IOC The implementation principle of container is not well understood , To put it bluntly , Just stay in the stage of being able to use , There is a heart that wants to read the source code ...

Random recommendation

  1. In depth understanding of CSS3 Animation Frame animation

    CSS3 I am here 5 It worked a year ago , Including the company's projects have been in the forefront of Technology . Recently, I'm writing about the theme of Qixi Festival on MOOCS , Used a lot of CSS3 Animation , But really precipitation down, carefully go deep CSS3 The attributes of animation are very deep , I'll write about frame motion here ...

  2. java20

    1: recursive ( understand ) (1) Method defines the phenomenon of calling method itself give an example : The old monk tells a story to the young monk , We learn programming (2) Recursion considerations : A: There must be an exit , Otherwise, it's dead recursion B: Not too many times , Otherwise, the memory overflows C: Construction methods cannot be recursive ...

  3. Bridge Pattern —— Object structured mode

    I saw it today Bridge Pattern , Make a simple summary of it , And give a few easy to understand article links . ( One ) Intention -- Separate the abstract from its implementation , So that they can all change independently . Applicable to types described from multiple dimensions , Take it apart , So that it can move along all dimensions ...

  4. nginx Limit access speed

    from :http://siwei.me/blog/posts/nginx-ip Reference resources :http://tengine.taobao.org/document_cn/http_limit_req_cn.ht ...

  5. com Study ( 5、 ... and )—— Implementing multiple interfaces

    From the fifth to the seventh , We use ATL I wrote a simple one COM Components , The reason is simple , Because in the component , Only one custom is implemented (custom) The interface of IFun. Of course, if you want to be lazy , We can 200 All functions add ...

  6. IOC Containers MEF stay MVC The use of

    I want to use my website framework recently IOC Under the transformation , After comparison , I initially chose autofac, although MEF No configuration required , But the performance is not good ,autofac Although you need to write your own automated injection , But the performance is very good . Let's first analyze the major IOC The performance of the frame , There are two kinds ...

  7. react.js Get real DOM node

    In order to get the real dom node , The text input box must have a  ref  attribute , then  this.refs.[refName]  Will return to this real DOM node . var MyComponent = React.crea ...

  8. python Of a,b=b,a+b and a=b b=a+b The difference between ( classic )

    I was just learning python When , I found that the following assignment is going to stun me ( Think for a long time ), So I sort it out and write my blog , I hope it will be helpful to my younger brother and younger sister in the future ! I love you forever ! ---- New baby n,a,b=0,0,1 while ...

  9. [Swift]LeetCode543. The diameter of a binary tree | Diameter of Binary Tree

    Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a b ...

  10. With cute new look springboot Source code 11(springboot Start the principle Source code )

    Through so many previous explanations ,springboot The principle should also have an outline , Some basic configuration , From the client url To controller( Configure some components to be used ,servlet Three components , Processor mapper , Interceptor , View parser these ...