Introduction to String class functions in standard C + + Note the string class in the C + + standard library is not the reason why CString discards the char* string, because he and the former do not have to worry about enough memory, string length, and so on, and appear as a class. His integrated operations function is sufficient to complete most of our cases (even 100%). We can use = for assignment operation, = = For comparison, + do series (is not very simple?). We can think of it as the basic data type of C + +. OK, 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 This is not string.h string.h is a C string header file #include <string> using namespace Std; 1. Declaring a C + + string declaring a string variable is simple: string Str; 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 for string is used directly, and this function is to initialize STR to an empty string. The constructors and destructors for the string class are as follows: a) string s; //Generate an empty string s B) string S (str)//copy constructor generates STR replica c) string s (str,stridx)//String str inside The part beginning with the position Stridx "as the initial value d of the string" string s (str,stridx,strlen)//The string str inside "starts at the Stridx and at most the length strlen "Part of the string as the initial value e) string s (CStr) The C string is used as the initial value of S (f) string S (chars,chars_len)///Chars_len The first character of the C string as the initial value of the string s. g) string S (num,c)//Generate a string containing num c character h) string s (Beg, End)//to destroy all characters in the range beg;end (not including end) as the initial value of the string s (i) s.~string ()//To free the memory is very simple, I do not explain. 2. String manipulation functions Here is the focus of C + + string, I first listed a variety of operational functions, do not like to read all the functions of the person can find their favorite function, and then to see his detailed explanation. A) =,assign () //Assign new value B) swap () //Exchange two-string contents C) +=,append (), Push_back ( ///At tail add character D) insert ()//Insert character E) erase ()//delete character F) clear ()//Remove all characters g) replace ()//Replace character H) +//series string i) ==,!=,< <=,>,>=,compare () //comparison string J) size (), Length () //return character quantity K) max_size ()// Returns the possible maximum number of characters L) empty () //Judging whether the string is empty m) capacity ()//return the character before reallocation (n) reserve ()//reserve a certain amount of memory to accommodate a certain number of characters O) [], at ()//Access single character P) >>,getline ()//read a value from stream Q) << //write value to stream R)Copy ()//Assign a value to a c_string s) c_str ()//() () ()//() () () () () ()//() () () () () () ()//() () () () () () () End ()//provides iterator support like STL x) Rbegin () rend ()//reverse iterator Y) get_allocator ()//Return configurator details below: 2. 1 C + + string and C-string conversion C + + provided by the C + + string corresponding to the C_string method is to use the data (), C_STR () and copy (), where the data () Returns the contents of the string as a character array, but does not add '/0 '. C_STR () returns an array of characters ending with '/0 ', while copy () copies or writes the contents of the string to an existing c_string or character array. C + + string does not end with '/0 '. My advice is to use C + + strings in your program, unless you have to choose C_string. As just a brief introduction, detailed introduction skimming, who would like to learn more about using the notes can give me a message (to my inbox). I explained in detail. 2. 2 size and capacity functions a C + + string exists in three sizes: a the number of existing characters, the function is size () and length (), and they are equivalent. Empty () is used to check whether the string is empty. b max_size () This size refers to the maximum number of characters that can be contained in the current C + + string, possibly in relation to the machine itself or the size of contiguous memory at the location of the string. We usually 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 the memory is reassigned. Another point to note here is the reserve () function, which allocates memory for string. The size of the reassignment is determined by its parameters, and the default parameter is 0, which makes a non-mandatory reduction to string. It is also necessary to repeat the problem of C + + string and C string conversion, many people will encounter such a problem, their own program to invoke other people's functions, classes and things (such as database connection function connect (char*,char*)), but other people's function parameters are char* form, And we know that c_str (), data ()The returned character array is owned by the string, so it is a const char* and must be copied to a char* to be the parameter of the function mentioned above, and our principle is not to use C strings. So, the way we handle this is this: if this function does not modify the contents of the parameter (i.e. char*), we can connect ((char*) Userid.c_str (), (char*) passwd.c_str ()), But there is a danger at this point, because the converted string can actually be modified (you can try it yourself), so I emphasize that unless the function is called without modifying the parameters, it must be copied to a char*. The safer way, of course, is to copy everything to a char*. At the same time we also pray that we still use the C string to program the masters (say they are a master is not too far, perhaps when we still wear pants, they began to program, haha ... ) write functions that are relatively canonical so that we do not have to cast them. 2. 3 element Access We can use the subscript operator [] and function at () to access the characters contained by the element. However, it should be noted that the operator [] does not check whether the index is valid (valid index 0~str.length ()), and if the index fails, it can cause undefined behavior. at () checks that if the index is invalid when you use at (), a Out_of_range exception is thrown. there is an exception to say that const string A; the operator [] is still valid for the index value of A.length (), and its return value is '/0 '. In all other cases, the A.length () index is invalid. Examples are: const string CSTR ("const string"); String Str ("string"); str[3]; //ok str.at (3); //ok str[100]; Undefined behavior str.at (MB); //throw out_of_range str[str.length ()] //undefined behavior Cstr[ Cstr.length ()]//return '/0 ' str.at (str.length ());//throw Out_of_range cstr.at (Cstr.lengTh ())////throw Out_of_range I do not approve of a reference or pointer assignment similar to the following: char& r=s[2]; char* p= &s[3]; Because once the redistribution occurs, the r,p immediately expires. The way to avoid it is to not use it. 2. 4 comparison functions C + + strings support common comparison operators (>,>=,<,<=,==,!=), and even support comparisons between string and c-string (such as Str < "Hello"). When using >,>=,<,<= these operators are compared according to the "current character attribute" by the dictionary order of the characters. The dictionary is sorted by a small character, the order of comparison is a backward comparison, and the unequal character is encountered to determine the size of two strings by comparing the two characters in that position. At the same time, string ("AAAA") <string (AAAAA). Another powerful comparison function is the member function compare (). He supports multi-parameter processing, which enables comparisons using index values and lengths to locate substrings. He returns an integer to indicate the comparison, and the return value is as follows: 0-equal 〉0-greater than <0-. Examples are as follows: string S ("ABCD"); s.compare ("ABCD"); return 0 s.compare ("DCBA"); Returns a value of less than 0 s.compare ("AB"); Returns a value greater than 0 S.compare (s); Equal S.compare (0,2,s,2,2); Use "AB" and "CD" to compare less than 0 s.compare (1,2, "bcx", 2); Compare "BC" and "BC". What do you think. The work can be all right. What the. It's not enough to satisfy your appetite. All right, wait, back there.There is a more personalized comparison algorithm. First give a hint, using the STL comparison algorithm. What the. The STL is a Greek. Come on, you have to rebuild. 2. 5 changing content This is a large part of the operation of the string. The first assignment, of course, is to use the operator = The new value can be a string (such as: 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 (), which allows you to more flexibly assign a value to a string. Or an example: S.assign (str); Do not say S.assign (str,1,3);//If STR is "Iamangel" is to assign "AMA" to string s.assign (Str,2,string::npos);//To assign string str from index value 2 to end to S S.assign ("Gaint"); Do not say S.assign ("Nico", 5);//assign ' n ' I ' C ' o '/0 ' to the string s.assign (5, ' X ');//Assign five x to string to empty the string by three: s= ""; S.clear (); S.erase ( ;(more and more I feel that it is easier for people to understand than to speak. )。 String provides a number of functions for inserting (insert), deleting (erase), replacing (replace), and adding characters. First of all, add the character (this is said to increase on the tail), the function has + =, append (), push_back (). Examples are as follows: s+=str;//add a string s+= "My name is JIAYP";//Add a C string s+= ' a ';//Add a character s.append (str); S.append (str,1,3)//does not explain the explanation of the previous function argument assign S.append (Str,2,string::npos)//does not explain S.append ("My name is Jiayp"); S.append ("Nico", 5); S.append (5, ' X '); S.push_back (' a ');//This function can only add a single character to the STL familiar understanding it's simple. Maybe you need to insert a string somewhere in the middle of it, and you can use the Insert () function, which requires you to specify an index of placement. The inserted string will be placed at the back of the index. S.insert(0, "my Name"); S.insert (1,STR); This form of insert () function does not support passing in a single character, at which point a single character must be written in a string form (disgusting). Now that you feel nauseous, you have to read the following paragraph: 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, iterator is char*, so it is not OK for you to invoke the Insert function: Insert (0,1, ' J '), which is the first argument to be converted to. So you have to write this: insert ((string::size_type) 0,1, ' J '). The second form points to the use of the iterator placement character, which is mentioned later. By the way, string has many operations that use STL iterators, and he tries to be as close to the STL as possible. Delete function erase () There are also several kinds of forms (I'm annoying. ), there are also several replacement functions replace (). For example: String s= "il8n"; S.replace (1,2, "nternationalizatio");//Replace the 2 from index 1 with the c_string s.erase (13) at the back;//Remove S.erase (7,5) from the beginning of index 13; Delete 5 2 from the beginning of index 7. 6 The function of extracting substring and string connection caption substring is: substr (), the form is as follows: S.substr (),//returns the entire contents of S s.substr (11);//S.substr (5,6) from the substring of the index 11;//6 characters starting from index 5 The function of combining two strings is +. (who don't understand, please call 120) 2. 7 Input and output operations
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service