The reason for discarding the char* string is to choose the string class in the C + + standard library because he does not have to worry about the adequacy of the memory, the length of the string, and so on, and as a class, his integrated operation function is sufficient to fulfill the needs of most of our cases (even 100%). We can use = To do the assignment, = = to compare, + do concatenation (is not very simple?). We can think of it as C + +the basic data type. Well, get to the point ... First, in order to use the string type in our program, we must include the header file<string>. As follows: #include<string>//Note that this is not string.h string.h is a C string header file1. Declaring a C + +The string declaration of a string variable is simple:stringStr; So we declare a string variable, but since it is a class, there are constructors and destructors. The above declaration does not pass in parameters, so the default constructor of string is used directly, and the function is to initialize STR to an empty string. The constructors and destructors for the string class are as follows: a)stringS//generates an empty string sbstringS (str)//copy constructor generates a copy of StrCstringS (STR,STRIDX)//treats the part of the string str "starting at position Stridx" as the initial value of the stringDstringS (Str,stridx,strlen)//The part of the string str "starting at STRIDX and at most strlen" as the initial value of the stringEstringS (CStr)//The C string as the initial value of SFstringS (Chars,chars_len)//The first Chars_len character of the C string as the initial value of the string s. GstringS (num,c)//generates a string that contains num characters cHstringS (beg,end)//The initial value of the string s as a character in the interval beg;end (not including the end)i) s.~string()//destroys all characters and frees up memoryIt's all very simple, and I won't explain it. 2. String manipulation function here is C++the focus of the string, I first put a variety of operational functions listed, do not like to read all the functions of the people can find their favorite functions, and then to see his detailed explanation. A)=,assign ()//assign a new valueb) Swap ()//swapping the contents of two stringsc) +=,append (), push_back ()//add characters at the taild) Insert ()//Insert Charactere) Erase ()//Delete characterf) Clear ()//Remove all charactersg) Replace ()//Replace characterh) +//concatenation stringi) ==,!=,<,<=,>,>=,compare ()//Comparing Stringsj) Size (), Length ()//returns the number of charactersk) Max_size ()//the maximum number of possible characters returnedL) Empty ()//determines whether a string is emptym) Capacity ()//returns the character capacity before ReallocationN) Reserve ()//keep a certain amount of memory to accommodate a certain number of characterso) [], at ()//accessing a single characterp) >>,getline ()//read a value from streamQ) <<//write a value to streamr) Copy ()//assign a value to a c_strings) c_str ()//return content as C_stringT) data ()//returns the content as a character arrayu) substr ()//return a substringV) Find function W) begin () End ()//provides iterator support similar to STLx) Rbegin () rend ()//Reverse IteratorY) Get_allocator ()//Return to Configuratorhere is a detailed description:2.1C++Conversion of strings and C strings CThe method provided by the C + + string to get the corresponding c_string is to use data (), C_str (), and copy (), where data () returns the string contents as an array of characters, but does not add ' \0’。 C_STR () returns a ' \0' At the end of the character array, and copy () copies or writes the contents of the string to an existing c_string or character array. C + + strings do not have a ' \0End My advice is that you can use C + + in your programthe string is used unless c_string is chosen as a last resort. Since it is just a brief introduction, detailed introduction brushing, who would like to further understand the use of the precautions can give me a message (to my inbox). I'll explain in detail. 2.2size and capacity function one C+ + strings exist in three sizes: a) The number of existing characters, the function is size () and length (), they are equivalent. Empty () is used to check if the string is empty. b) max_size () This size refers to the current C + +the maximum number of characters a string can contain is probably related to the limitations of the machine itself or the size of contiguous memory where the string is located. We generally do not care about him, should be large enough for us to use. But not enough, it throws Length_error exception C) capacity () the maximum number of characters a string can contain before reallocating memory. Another point to note here is the reserve () function, which re-allocates memory for string. The size of the reallocation is determined by its parameters, and the default parameter is 0, which is a non-mandatory reduction of string. There's a need to repeat C .+ + string and C string conversion problems, many people will encounter such problems, their own programs to call other people's functions, classes and so on (such as database connection function connect (Char*,Char*), but the function parameters of others are in char* form, and we know that the character array returned by C_STR () and data () is owned by the string, so it is a constChar*, to be a parameter of the function mentioned above, it must also be copied to a char*, and our principle is that we can not use the C string. So, the way we do this is if this function does not modify the contents of the parameter (that is, char*), we can do so with connect (Char*) Userid.c_str (), (Char*) Passwd.c_str ()), but at this time there is a danger, because the converted string is actually modifiable (you can try it yourself), so I emphasize that unless the function is called, the parameter will not be modified, otherwise it must be copied to a char*. Of course, a more secure approach is to copy any situation to a char*.up. At the same time, we also pray that we still use C strings to program the experts (said they are a master not a bit too, perhaps when we still wear diaper when they began programming, haha ... The functions written are more canonical, so we don't have to cast them. 2. 3 element Access We can use the subscript operator [] and the function at () to access the characters contained in the element. However, it should be noted that the operator [] does not check that the index is valid (valid index 0~str.length ()), which causes undefined behavior if the index is invalidated. The at () checks if the index is invalid when using at () and throws an Out_of_range exception. One exception has to be said,Const stringA; the operator [] is still valid for the index value a.length (), and its return value is ' \0'. In all other cases, the A.length () index is invalid. Examples are as follows:Const stringCstr ("Const string");stringSTR ("string"); str[3];//OKStr.at (3);//OKstr[ -];//undefined behaviorStr.at ( -);//Throw Out_of_rangeStr[str.length ()]//no behavior definedCstr[cstr.length ()]//back to ' + 'Str.at (Str.length ());//Throw Out_of_rangeCstr.at (Cstr.length ())////throw Out_of_rangeI do not approve of a reference or pointer assignment similar to the following:Char& r=s[2];Char* p= &s[3]; R,p immediately fails as soon as a redistribution occurs. The way to avoid this is to not use it. 2. 4 comparison function CThe + + string supports common comparison operators (>,>=,<,<=,==,!=) and even supports string comparisons with c-string (such as str< "Hello"). When using the >,>=,<,<= operators, the characters are compared in dictionary order according to the current character attribute. Dictionaries are smaller than the previous characters, and the order of comparison is compared from front to back, and the size of the two strings is determined by the comparison of the two characters in this position by encountering unequal characters. Whilestring("AAAA") <string(AAAAA). Another powerful comparison function is the member function compare (). He supports multi-parameter processing and supports comparisons with index values and length-locating substrings. He returns an integer representing the result of the comparison, and the return value has the following meanings:0Equal0-Greater than <0-less than. Examples are as follows:strings ("ABCD"); S.compare ("ABCD"); //returns 0S.compare ("DCBA");//returns a value that is less than 0S.compare ("AB");//returns a value greater than 0S.compare (s);//EqualS.compare (0,2, S,2,2);//compare less than 0 with "AB" and "CD"S.compare (1,2, "Bcx",2);//compare with "BC" and "BC". How about that? Work can be full of it! What the? Not enough to satisfy your appetite? Well, wait, there's a more personal comparison algorithm behind it. Give a hint first, using the STL's comparison algorithm. What the? Do you have a very ignorant stl? Come on, you've rebuilt it! 2.5Change the content this takes up a large part of the operation of the string. First of all, the assignment, the first assignment method, is to use the operator=, the new value can be a string (for example: S=ns), c_string (such as: s= "Gaint") or even a single character (such as: s=' J '). You can also use the member function assign (), a member function that gives you more flexibility in assigning a value to a string. Or an example: S.assign (str); //Don't sayS.assign (str,1,3);//if STR is "Iamangel", it is to assign "AMA" to the stringS.assign (str,2,string:: NPOs);//assigns the string str from the index value 2 to the end of the SS.assign ("Gaint");//Don't sayS.assign ("Nico",5);//assign ' n ' I ' C ' ' O ' to the stringS.assign (5, ' X ');//assigning five x to a stringThere are three ways to clear a string: s="; S.clear (); S.erase ();(I feel more and more like an example than speaking to make others easy to understand! )。 String provides a number of functions for inserting (insert), deleting (erase), replacing (replace), and adding characters. First say increase the character (which is said here is on the tail), the function has+=, append (), push_back (). Examples are as follows: s+=STR;//Add a Strings+= "My Name isJIAYP ";//Add a C strings+= ' a ';//Add a characters.append (str); S.append (str,1,3);//does not explain the interpretation of the same previous function parameter assignS.append (str,2,string:: NPOs)//no explanation.S.append ("My Name isJIAYP "); S.append (" Nico ",5); S.append (5, ' x '); S.push_back (' a ') ;//This function can only add a single character to the STL familiarity is easy to understandPerhaps you need to insert a string somewhere in the middle of the string, and you can use the Insert () function, which requires you to specify an index of the placement, and the inserted string will be placed behind the index. S.insert (0, "my Name"); S.insert (1, str); This form of the insert () function does not support passing in a single character, where a single character must be written as a string (disgusting). Now that you feel nauseous, you have to read the following passage: To insert a single character, the Insert () function provides two overloaded functions for inserting a single character operation: Insert (Size_type index,size_type num,chart c) and insert (iterator Pos,size_type Num,chart c). Where Size_type is an unsigned integer and iterator is char*, so it's not possible for you to call the Insert function this way: insert (0,1, ' J '); When will the first parameter be converted to? So you have to write this: insert (string:: Size_type)0,1, ' J ')! The second form points out the form of inserting characters using iterators, which is mentioned later. By the way, string has a lot of operations that use STL's iterators, and he tries to do the same with STL. There are several ways to delete a function erase () (it's annoying!). ), replacing the function replace () also has several. For example:strings="il8n"; S.replace (1,2, "Nternationalizatio");//2 from index 1 replaced with the back c_stringS.erase ( -);//Delete all from index 13S.erase (7,5);//Delete 5 from the beginning of index 72. 6 extract substring and string concatenate the function of the substring is: substr (), the form is as follows: S.substr ();//returns the full contents of SS.SUBSTR ( One);//sub-string from index 11 backwardsS.SUBSTR (5,6);//starting from index 5 6 charactersThe function of combining two strings is +. (Who doesn't understand, please call us)2. 7 input/output operation1. >>reads a string from the input stream. 2. <<writes a string to the output stream. Another function is Getline (), which reads a line of content from the input stream until it encounters a break or ends at the end of the file. 2. 8 Search and find lookup functions are many and powerful, including: Find () RFind () find_first_of () find_last_of () find_first_not_of () Find_last_not _of () These functions return the index of the first character in the range of characters that match the search criteria, and return NPOs if no target is found. The parameters of all functions are described as follows: The first parameter is the object being searched. The second parameter (optional) indicates the search starting index within the string, and the third parameter (optional) indicates the number of characters searched. Relatively simple, not much to say that do not understand can be presented to me, I will answer carefully. Of course, a more powerful STL search will be mentioned later. At last say the meaning of NPOs,string:: The type of NPOs is String::size_type, so once you need to compare an index to NPOs, the index value must be string::size) type, and in more cases, we can directly compared the function and NPOs (for example:if(S.find ("jia") = =string:: NPOs)).
String--c++ Series