Introduction to string :

A string is a series of characters stored in continuous bytes in memory .C++ There are two styles of handling strings in , One from C language , be called C style of language ; Another style is based on string library , Let's call it string Library style . among C style of language , It makes use of the character that string is stored in continuous byte in memory , Stores a string in a character array , with ‘\0’ ending ; and string Methods provided by library style , Allows programmers to use strings as variables , Next, we will introduce these two styles respectively .

1.C style of language
(1) Strings and character arrays

C Language style is handled by placing strings in character arrays , Each character is in an array element , And null character (’\0’) ending . Null terminated pair C Language style is very important for strings , This is the mark that distinguishes a string from an array of characters , such as :
char a[5] = {'1','2','3','4','5'}; // This is an array of characters char b[5] = {'1','2','3','4','\0'
}; // This is a string

meanwhile , The null character at the end of a string is also a mark used by many functions to determine whether to reach the end of a string , If an element in the string is set to ’\0’, So many functions will misjudge the end of the string and bring errors , such as :
char dog[6] = {'T','e','d','d','y','\0'}; // Define a string Teddy cout<<" Before the change : "<<dog<<
"\n"; //cout Will be output until a null character at the end is encountered dog[2] = '\0'; // Change the character 'd' Change to null character cout<<" After the change : "<<dog;
The result of the execution of such a code segment will be :

If the user does not set the end of the character array to a null character ,cout The function continues to interpret the rest of memory as elements to be printed until a null character is encountered , However, null characters are common in memory , So the output will stop soon , Most of this will not affect the output , However, users should still not use non null character ending strings as strings .
(2) Initialization of string

The initialization of the string can be done as in the previous example , Use single quotation marks to separate single characters and put a space character at the end , But this is cumbersome . A simpler way to initialize a character array to a string is to use double quotation marks ("") Enclose the content . This string is called a string constant , Or string literal . A quoted string implicitly contains a null character at the end , It doesn't need to be added artificially , But remember to reserve space for it . When you enter a string like this , We can manually set the length of the character array , You can also let the compiler compute space automatically , such as :
char dog[6] = "Teddy" // Artificial setting , Reserve an empty character position char cat[] = "Persion" // Compiler calculation
It should be noted that , A large enough space should be allocated for the string , If there is an unused part of the allocated space , Will be automatically set to null character ’\0’
(3) String splicing and character operation in string

stay C In language style , Arithmetic operator ’+‘ Will not be interpreted as a concatenation of strings , So it can't be used directly ’+' Splicing two strings . You can use functions strcat() Achieve the goal , But you need to use string library , So let's talk about it below .
After understanding the relationship between string and character array , You can use the properties of the array to operate the characters in the string , For example, the realization of a word case conversion :
char dog[6] = "Teddy"; for (int i=0;i<6;i++){ // If the length is unknown , have access to strlen(dog) obtain if(dog
[i]<'Z' && dog[i]>'A'){ dog[i] += 32; } else{ dog[i] -= 32;
(4) String input

Just like character arrays , String can be used cin Input . however cin Use blank ( Space , Line break , Tab ) Determine input boundary , This means that the input string cannot contain spaces ( You can only enter one word at a time ), The problem is obvious .
But actually , If spaces and newlines have the same effect on the confirmation boundary , So does it mean that the same result will appear when running the program ? For example, the following code :
char name[10]; char food[10]; cout<<"What is your name:"; cin>>name; cout<<
"What is your favorite food:"; cin>>food; cout<<name<<" likes "<<food;
If you use line breaks , That is, use carriage return to separate two strings , The running example is :

It seems that there is no problem , But what if you use spaces to split ?

under these circumstances , Programmers have not yet responded to the input of favorite foods , The program has shown it . This is because after using spaces ,rice Is left in the input queue , Therefore, when the program searches the input results in the input queue, it finds the data left in it rice, Read directly and store in string , In this way, the user does not need to input any more .

first , It's not good to input only one word at a time , however istream Classes in provide some class member functions , Line oriented input is possible , That is to say, just put the newline character ( Press enter) As the end of input flag . What are the advantages of such a function getline() and get() two types .

The difference is that getline() The newline character is read and discarded , and get() The newline character is kept in the input queue . The general form of these two functions is :cin.getline(arrayName,arrayLenth) and cin.get(arrayName,arrayLenth); The delegate puts the input in the arrayLenth Of length arrayName In the array of . This solves some of the problems associated with using spaces as input boundaries , such as :
char name[15]; cout<<"input name:"; cin.getline(name,15); cout<<name;
The test example is :

You can see that you can enter a string with spaces !
But we need to pay attention , because get() Function leaves the carriage return in the queue , You may need another one get() To read carriage returns , Otherwise, it will bring problems to the input , such as :
char pets[10]; char food[10]; cin.get(pets,10); cin.get();
// Offsets the string left in the input queue , It can also be used getchar() cin.get(food,10); cout<<pets<<"\n"; cout<<food;
2.string Library style ( join cstring perhaps string.h)
By adding string Class extends C++ library , You can use it now string A variable of type, rather than an array of characters, stores a string . Now you can define strings like this :
string pets = "dog and cat";
(1) assignment , Splicing and attaching
string first_name; string last_name; first_name = "Mercer"; // Assigning values to string variables
last_name= "Alex"; cout<<last_name+" ,"+first_name; // Here "+" Interpreted as string splicing
(2) Connection with character array
actually string Class definition hides the array nature of a string , actually string There are many similarities with character arrays , There are also some differences , Take a test program as an example :
string first_name = "Alex"; // You can use it C Style string initializes the string object string last_name; cin>>
last_name; // have access to cin Read from keyboard to string Object cout<<"full_name: "<<first_name+last_name<<
"\n";// You can use it cout output cout<<first_name[0]; // You can use array representation to output characters in a string
(3)string Input of

string Class can be used cin and >> Input , But with C The language style is the same , Facing the problem that the space may bring . But before C In language style , We use getline(),get() Time , You need to determine the name and length of the character array , however string Class hides the array property , How to input ? You can use functions getline(cin,str) To input , for example :
string full_name; getline(cin,full_name);
(4) Some common functions
①strcpy -- Copies a string into a character array
strcpy(a,b), Set the array b Copy to a in , It will cover the original a Content in ;
char a[4] = "123"; char b[4] = "456"; cout<<strcpy(a,b);
The results are as follows

②strcat -- Appends a string to the end of the string
strcat(a,b), Set the array b Attach to a end , The same is just in the case
char a[4] = "123"; char b[4] = "456"; cout<<strcat(a,b);
The results are as follows :

③strlen -- Output string length
char a[4] = "123"; cout<<strlen(a);
The results are as follows :

Here we need to pay attention , The length of the character array is 4, The length of the output is 3, This is because a reserved element position is implicitly added to the quoted content ’\0’ It's reserved , and strlen() The function stops when it encounters a null character , It is not counted in string length , It's also a side effect of what we're saying C The view of language style string initialization .

©2020 ioDraw All rights reserved
0.96OLED display -4 Line SPI explain C++11 of std::function,std::bind,std::placeholdersJavaScript study ( Function declaration and parameters )QTabWidget Style sheet settings The project passed idea Package and publish to tomcat The server postman Interface test get timestamp and MD5 encryption react Background management configuration route and sidebar :python Simple game code -10 Minutes Python Write a snake game , simple You know? Python What does the foundation include ? Learn something ?10 individual Python Introduction to crawler