First, in order to use the string type in our program, we must include the header file. As follows:
#include//Note this is not string.h string.h is a C string header file
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 constructors generate a replica of STR
c) string s (str,stridx)//Stridx the part of the string str "beginning with position" as the initial value of the string
d) string s (str,stridx,strlen)//Stridx the part of the string str "beginning with the length of strlen" as the initial value of the string
e) string s (CStr)//The C string 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 characters
h) string S (beg,end)//The initial value of the string s as a character in the interval beg;end (not including end)
i) s.~string ()//Destroy all characters, free memory
It's simple, I don't explain it.
2. String manipulation functions
Here is the focus of C + + string, I first listed a variety of operating 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 a new value
b) Swap ()//Exchange two-string contents
c) +=,append (), push_back ()///Add character at tail
D insert ()//Insert character
e) Erase ()///delete character
f) Clear ()//Remove all characters
g) Replace ()//Replace character
h) +//concatenated string
i) ==,!=,<,<=,>,>=,compare ()//comparison string
j) Size (), Length ()//return number of characters
k) max_size ()//returns the possible maximum number of characters
L) empty ()//To determine whether the string is empty
m) Capacity ()//returns the character capacity before redistribution
N) reserve ()//reserve a certain amount of memory to accommodate a certain number of characters
o) [], at ()//Access single character
p) >>,getline ()//reading a value from stream
Q <<//To write the value of the profit stream
r) Copy ()//Assign a value to a c_string
s) c_str ()//return content to C_string
T) data ()//returns the content as a character array
u) substr ()//Return of a substring
V) Lookup function
W) begin () end ()//provide iterator support similar to STL
x) Rbegin () rend ()//Reverse iterators
Y) Get_allocator ()//Return Configurator
Here is a detailed description:
2. 1 C + + string and C-string conversions
C + + provides a c_string method for C + + strings that uses data (), C_str (), and copy (), where data () returns the contents of the string as a character array, but does not add '. C_STR () returns an array of characters that end with ', ' and copy () copies or writes the contents of the string to an existing c_string or character array. C + + strings do not end With ' ". 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 existing number of 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 the character array returned by C_STR (), data () is owned by the string, so it is a const char* and must be copied to a char* as an argument to the function mentioned above, and our principle is not to use a C string. 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.
One exception to this is that const string A; the operator [] is still valid for the index value of A.length (), and its return value is ' yes '. In all other cases, the A.length () index is invalid. Examples are as follows:
Const string CSTR ("const string");
String Str ("string");
STR[3]; Ok
str.at (3); Ok
STR[100]; Undefined behavior
str.at (100); Throw Out_of_range
Str[str.length ()]//undefined behavior
Cstr[cstr.length ()]//return ' to '
Str.at (Str.length ());//throw Out_of_range
Cstr.at (Cstr.length ())////throw Out_of_range
I don't 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. The 4 comparison functions
C + + strings support common comparison operators (>,>=,<,<=,==,!=) and even support comparisons of 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") another powerful comparison function is a 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");//return a value less than 0
s.compare ("AB"); Returns a value greater than 0
S.compare (s);//Equality
s.compare (0,2,s,2,2);///"AB" and "CD" For comparison less than 0 s.compare (1,2, "bcx", 2); Compare "BC" and "BC".
How about. The work can be all right. What the. It's not enough to satisfy your appetite. Well, wait, there's a more personalized comparison algorithm behind it. First give a hint, using the STL comparison algorithm. What the. The STL is a Greek. Come on, you have to rebuild.
2. 5 Change Content
This accounts for a large portion of the operation of strings.
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. Let me give you an example:
S.assign (str); Don't say
S.assign (str,1,3)//If STR is "Iamangel" is assigned "AMA" to string s.assign (Str,2,string::npos);//String STR is assigned to s from index value 2 to the end.
S.assign ("Gaint"); Don't say
S.assign ("Nico", 5);//assign ' n ' I ' C ' o ' to the string
S.assign (5, ' X ');//Assign five X to string
There are three ways to empty a string: s= ""; S.clear (); S.erase ();(I'm getting more and more comfortable with examples than talking to others. )。
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;//plus 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 same previous function parameter assign
S.append (Str,2,string::npos)//no explanation.
S.append ("My name is Jiayp");
S.append ("Nico", 5);
S.append (5, ' X ');
String manipulation is a big topic, in standard C + +, the string string class becomes a standard, the reason for discarding the char* string and choosing the string class in the C + + standard library is because he and the former do not have to worry about enough memory, string length, etc. And as a class, he integrates an operation that is sufficient to accomplish most of our needs.
Let's start with some examples to learn the use of the string class below.
1)
#include <string>
#include <iostream>
using namespace Std;
void Main ()
{
string s ("hehe");
cout<<s<<endl;
Cin.get ();
}
2)
#include <string>
#include <iostream>
using namespace Std;
void Main ()
{
Char chs[] = "hehe";
string s (CHS);
cout<<s<<endl;
Cin.get ();
}
3)
#include <string>
#include <iostream>
using namespace Std;
void Main ()
{
Char chs[] = "hehe";
string s (chs,1,3); Specify starting with index 1 of CHS, and finally copying 3 bytes
cout<<s<<endl;
Cin.get ();
}
4)
#include <string>
#include <iostream>
using namespace Std;
void Main ()
{
String S1 ("hehe");
String S2 (S1);
cout<<s2<<endl;
Cin.get ();
}
5)
#include <string>
#include <iostream>
using namespace Std;
void Main ()
{
String S1 ("hehe", 2, 3);
String S2 (S1);
cout<<s2<<endl;
Cin.get ();
}
6)
#include <string>
#include <iostream>
using namespace Std;
void Main ()
{
Char chs[] = "hehe";
string s (chs,3); Constructs the first 3 characters of the CHS as initial values
cout<<s<<endl;
Cin.get ();
}
7)
#include <string>
#include <iostream>
using namespace Std;
void Main ()
{
String s (Ten, ' K '); Assign 10 characters, the initial value is ' K '
cout<<s<<endl;
Cin.get ();
}
The above is a simple way to construct a string class instance.
9)
Assign new value
#include <string>
#include <iostream>
using namespace Std;
void Main ()
{
String s (Ten, ' K '); Assign 10 characters, the initial value is ' K '
cout<<s<<endl;
s = "Hehehehe";
cout<<s<<endl;
S.assign ("Kdje");
cout<<s<<endl;
S.assign ("FKDHFKDFD", 5); Reassign the first 5 element contents of the specified string
cout<<s<<endl;
Cin.get ();
}
10)
Swap method Exchange
#include <string>
#include <iostream>
using namespace Std;
void Main ()
{
string S1 = "hehe";
String s2 = "Gagaga";
cout<< "S1:" <<s1<<endl;
cout<< "S2:" <<s2<<endl;
S1.swap (S2);
cout<< "S1:" <<s1<<endl;
cout<< "S2:" <<s2<<endl;
Cin.get ();
}
11)
+=,append (), push_back () add character at tail
#include <string>
#include <iostream>
using namespace Std;
Void Main ()
{
string s = "hehe";
s = "Gaga";
cout<<s<<endl;
s.append ("hehe"); //append () method can add a string
cout<<s <<endl; The
s.push_back (' K '); //push_back () method can only add one character ...
cout<<s<<endl;
cin.get ();
}
//insert () inserts a character. In fact, insert is good, and other insert operation is the same.
#include <string>
#include <iostream>
using namespace std;
void Main ()
{
string s = "hehe";
S.insert (0, "Head"); Insert in head
S.insert (S.size (), "tail"); Insert in tail
S.insert (S.size ()/2, "Middle");//Insert in middle
cout<<s<<endl;
Cin.get ();
}
13)
#include <string>
#include <iostream>
using namespace Std;
void Main ()
{
string s = "ABCDEFG";
S.erase (0,1); From index 0 to index 1, delete ' a '
cout<<s<<endl;
In fact, you can also use the Replace method to perform a delete operation
S.replace (2,3, "");//will replace the specified range of characters with "", that is, the disguise deleted
cout<<s<<endl;
Cin.get ();
}
14)
Clear () Remove all characters
#include <string>
#include <iostream>
using namespace Std;
void Main ()
{
string s = "ABCDEFG";
Cout<<s.length () <<endl;
S.clear ();
Cout<<s.length () <<endl;
Use the Earse method to remove all the disguised
s = "DKJFD";
Cout<<s.length () <<endl;
S.erase (0,s.length ());
Cout<<s.length () <<endl;
Cin.get ();
}
15)
Replace () substitution character
#include <string>
#include <iostream>
using namespace Std;
Void Main ()
{
string s = "ABCDEFG";
s.replace (2,3, "!!!!!"); /Replace the word Fu Quan with "!!!!!" starting at index 2 and 3 bytes
cout<<s<<endl;
cin.get ();
}
//==,!=,<,<=,>,>=,compare () comparison string
#include <string>
#include <io Stream>
using namespace std;
void Main ()
{
string S1 = "ABCDEFG";
String s2 = "ABCDEFG";
if (S1==S2) cout<< "S1 = = S2" <<endl;
else cout<< "S1!= S2" <<endl;
if (S1!=S2) cout<< "S1!= S2" <<endl;
else cout<< "S1 = = S2" <<endl;
if (S1>S2) cout<< "S1 > s2" <<endl;
else cout<< "S1 <= S2" <<endl;
if (S1<=S2) cout<< "S1 <= S2" <<endl;
else cout<< "S1 > s2" <<endl;
Cin.get ();
}
17)
Size (), length () returns the number of characters
#include <string>
#include <iostream>
using namespace Std;
void Main ()
{
string s = "ABCDEFG";
Cout<<s.size () <<endl;
Cout<<s.length () <<endl;
Cin.get ();
}
18)
Max_size () returns the possible maximum number of characters
#include <string>
#include <iostream>
using namespace Std;
void Main ()
{
string s = "ABCDEFG";
Cout<<s.max_size () <<endl;
Cin.get ();
}
19)
Empty () to determine whether the string is empty
#include <string>
#include <iostream>
using namespace Std;
void Main ()
{
string S;
if (S.empty ())
cout<< "s is empty." <<endl;
Else
cout<< "s is not empty." <<endl;
s = s + "ABCDEFG";
if (S.empty ())
cout<< "s is empty." <<endl;
Else
cout<< "s is not empty." <<endl;
Cin.get ();
}
20)
[], at () access to single character
#include <string>
#include <iostream>
using namespace Std;
void Main ()
{
string s = "abcdefg1111";
cout<< "Use []:" <<endl;
for (int i=0; i<s.length (); i++)
{
cout<<s[i]<<endl;
}
cout<<endl;
cout<< "Use at ():" <<endl;
for (int i=0; i<s.length (); i++)
{
cout<<s.at (i) <<endl;
}
cout<<endl;
Cin.get ();
}
21)
#include <string>
#include <iostream>
using namespace Std;
void Main ()
{
string s = "abcdefg1111";
const char * CHS1 = S.C_STR ();
const char * CHS2 = S.data ();
cout<< "use at ():" <<endl;
int i;
for (i=0; I<s.length (); i++)
{
& nbsp; cout<< "C_str ():" <<chs1[i]<<endl;
cout<< "data ():" <<chs2[i]<<endl;
}
cout<< "C_str ():" <<chs1<<endl;
cout<< "data ():" <<chs2<<endl;
cout<<endl;
cin.get ();
}
//substr () returns a substring
#include <string>
#include <iostream>
using namespace Std
Void Main ()
{
string s = "abcdefg1111";
String str = S.SUBSTR (5,3);//starting from index 5 3 bytes
cout<<str<<endl;
cin.get ();
}
//Find lookup function
#include <string>
#include <iostream>
using namespace std;
void Main ()
{
string s = "abcdefg1111";
String pattern = "FG";
String::size_type POS;
pos = S.find (pattern,0); Start with index 0 to find the header index that matches the string "F"
cout<<pos<<endl;
String str = S.SUBSTR (Pos,pattern.size ());
cout<<str<<endl;
Cin.get ();
}
24)
Begin () end () provides iterator support similar to STL
#include <string>
#include <iostream>
using namespace Std;
void Main ()
{
string s = "abcdefg1111";
for (String::iterator iter = S.begin (); Iter!=s.end (); iter++)
{
cout<<*iter<<endl;
}
cout<<endl;
cin.get ();
}
a C + + string has three sizes: a) The existing number of 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