After the introduction C# After string processing method , Let's talk about it C++ String handling method of .C++ The string processing method for does not C# The convenience of , It doesn't offer a lot of ideas C#
Such a practical function . Existing in the standard library string Type and traditional C String provides greater convenience .
comparison char* String of ,C++ In the standard library string class ,
With don't worry about enough memory , String length and so on , And as a class , He's integrated with enough functions to do most of our work ( Or even 100%) Needs of . We can use =
Perform assignment operation ,== Compare ,+ Make a series （ Is it very simple ?）. We can think of it as C++ Basic data types for .
first , For use in our program string type , We must include the header file . as follows ：
#include <string>// Notice it's not here string.h string.h yes C String header file
1. Declare a C++ character string
It's easy to declare a string variable ：string Str;
So we declare a string variable , But since it's a class , There are constructors and destructors . The declaration above has no arguments passed in , So I used it directly string
Default constructor for , What this function does is Str Initialize to an empty string .String The constructors and destructors of the class are as follows ：
a) string s; // Generate an empty string s
b) string s(str) // copy constructor generate str Copy of
c) string s(str,stridx) // String str within “ From position stridx” As the initial value of the string
d) string s(str,stridx,strlen) // String str within “ From stridx And the length is at most strlen” As the initial value of the string
e) string s(cstr) // take C String as s Initial value of
f) string s(chars,chars_len) // take C Before string chars_len Characters as string s Initial value of .
g) string s(num,c) // Generate a string , contain num individual c character
h) string s(beg,end) // By interval beg;end( Not included end) Characters in as strings s Initial value of
i) s.~string() // Destroy all characters , Free memory
2. String manipulation function
Here is C++ Focus of string , I'll list all kinds of operation functions first , People who don't like to read all the functions can find their favorite functions here , I'll see his detailed explanation later .
a) =,assign() // Assign new value
b) swap() // Exchange the contents of two strings
c) +=,append(),push_back() // Add character at end
d) insert() // Insert character
e) erase() // Delete character
f) clear() // Delete all characters
g) replace() // Replace character
h) + // Concatenation string
i) ==,!=,<,<=,>,>=,compare() // Compare strings
j) size(),length() // Number of return characters
k) max_size() // Return the maximum number of characters possible
l) empty() // Judge whether the string is empty
m) capacity() // Return the character capacity before reallocation
n) reserve() // Reserve a certain amount of memory to hold a certain number of characters
o) [ ], at() // Access single character
p) >>,getline() // from stream Read a value
q) << // Write value stream
r) copy() // Assign a value to a C_string
s) c_str() // Add content to C_string return
t) data() // Return content as a character array
u) substr() // Return a substring
v) Find function
w)begin() end() // Provide similar STL Iterator support for
x) rbegin() rend() // Reverse Iterators
y) get_allocator() // Return to Configurator
Here is a detailed introduction ：
3. C++ String and C String conversion
C++ Provided by C++ String to get the corresponding C_string Using the data(),c_str() and copy(), among ,data()
Returns the string contents as an array of characters , But not added ’\0’.c_str() Return to a ‘\0’ Array of characters at the end , and copy() Copy or write the contents of the string to the existing
c_string Or in character array .C++ String does not ’\0’ ending . My suggestion is that it can be used in the program C++ String is used , Unless you have to c_string.
4. Size and capacity functions
One C++ There are three sizes of strings ：a) Existing characters , The function is size() and length(), They are equivalent .Empty() 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 , It is likely to be related to the limitation of the machine itself or the continuous memory size of the string location . We don't usually care about him , It should be big enough for us . But not enough , Will throw
length_error abnormal c)capacity() Before reallocating memory string Maximum number of characters . Another thing to point out here is reserve() function , This function is
string Reallocate memory . The size of the reallocation is determined by its parameters , The default parameter is 0, It's going to be right string Non mandatory reduction .
It's necessary to repeat C++ String and C Problems in string conversion , Many people will encounter such problems , Self made programs call other people's functions , What kind of （ For example, database connection function
Connect(char*,char*)）, But other function parameters use char* Formal , And we know ,c_str(),data()
The returned character array is owned by the string , So it's a const char*, To be an argument to the function mentioned above , You must also copy to a char*, And our principle is not to use it C
String is not used . that , At this time, the way we deal with it is ： If this function ( that is char*) If the content of , We can do this
But there's a danger , Because the converted string can be modified , So I stress that unless the parameters are not modified when the function is called , Otherwise, you must copy to a char*
up . of course , A more secure way is to copy everything to one char* up . And we pray that it's still in use C Experts in string programming
The functions written are relatively standard , So we don't have to force it .
5. Element access
We can use the subscript operator  Sum function at() Access the characters contained in the element . But it should be noted that operators  Does not check whether the index is valid （ Valid index 0~str.length()
）, If the index fails , Causes undefined behavior . and at() Will check , If using at() When the index is invalid , Will throw out_of_range abnormal .
There's an exception to that ,const string a; Operators for  The index value is a.length() Still valid , Its return value is ’\0’. Other situations ,a.length()
Indexes are invalid . For example: ：
const string Cstr(“const string”);
Str; // Undefined behavior
Str.at(100); //throw out_of_range
Str[Str.length()] // Undefined behavior
Cstr[Cstr.length()] // return ‘\0’
Cstr.at(Cstr.length()) ////throw out_of_range
I don't approve of references or pointer assignments like the following ：
char* p= &s;
Because in the event of reallocation ,r,p Immediate failure . The way to avoid it is not to use it .
6. Comparison function
C++ String supports common comparison operators （>,>=,<,<=,==,!=）, Even support string And C-string Comparison of ( as str<”hello”). in use
>,>=,<,<= These operators are based on “ Current character properties ”
Compare characters one by one in dictionary order . Small characters before dictionary sorting , The order of comparison is from front to back , When encountering unequal characters, determine the size of the two strings according to the comparison results of the two characters in this position . meanwhile ,
Another powerful comparison function is the member function compare(). He supports multiparameter processing , Support index value and length positioning substring for comparison . He returns an integer to represent the result of the comparison , The meaning of the return value is as follows ：
0- equal 〉0- greater than <0- less than . For example: ：
s.compare(“abcd”); // return 0
s.compare(“dcba”); // Return a less than 0 Value of
s.compare(“ab”); // Return greater than 0 Value of
s.compare(s); // equal
s.compare(0,2,s,2,2); // use ”ab” and ”cd” Compare Less than zero
s.compare(1,2,”bcx”,2); // use ”bc” and ”bc” compare .
You can also use STL Comparison algorithm of
7. Change content
This is a large part of string operations .
First of all, assignment , The first method of assignment, of course, uses operators =, The new value can be string( as ：s=ns) ,c_string( as ：s=”gaint”) Even a single character （ as ：s=’j’
）. You can also use member functions assign(), This member function allows you to more flexibly assign values to strings . Let's give an example ：
s.assign(str); // No
s.assign(str,1,3);// If str yes ”iamangel” Is to ”ama” Assign to string
s.assign(str,2,string::npos);// String str From index value 2 From beginning to end s
s.assign(“gaint”); // No
s.assign(“nico”,5);// hold ’n’ ‘I’ ‘c’ ‘o’ ‘\0’ Assign to string
s.assign(5,’x’);// Put five x Assign to string
There are three ways to empty a string ：s=””;s.clear();s.erase();( More and more, I feel that examples are easier to understand than words !).
string Many functions are provided for insertion （insert）, delete （erase）, replace （replace）, Add character .
First, add characters （ The increase here is on the tail ）, Functions have +=,append(),push_back(). For example: ：
s+=str;// Add a string
s+=”my name is jiayp”;// Add one C character string
s+=’a’;// Add characters
s.append(str,1,3);// No explanation Same as previous function parameters assign Interpretation of
s.append(str,2,string::npos)// No explanation
s.append(“my name is jiayp”);
String manipulation is a big topic , In standard C++ in ,string String class becomes a standard , Why abandon char* String of C++ In the standard library string
class , It's because he's compared to the former , Don't worry about enough memory , String length and so on , And as a class , His integrated operation function is enough to fulfill our needs in most cases .