First, initialize
strings1="I Love you"; stringS2 (S1);//Initialize the S2 to a copy of S1, note that it cannot be written as a string S2; S2 (s1); stringS3 ("value");//Initializes a s3 copy of the string value stringS4 (6,'s');//Initialize S4 to 10 copies of character ' s ' /*Note string literals are not the same type as standard library string*/cout<<s1<<Endl; cout<<s2<<Endl; cout<<s3<<Endl; cout<<s4<<endl;
Results
Second, input
string S6; Getline (CIN,S6); // enter a string with spaces to test "Hello World" cout<<s6<<Endl;
cout<< "------------------------------" <<endl; string S5; CIN>>s5; // enter a string without spaces "Hello World" test, found only valid characters are read to the end of a space encounter cout<<s5<<Endl; // deliberately put S5 and S6 upside down, if first with CIN input S5, then use Getline (CIN,S6) will have problems.
Results
Third, access character
cout<<s1.at () <<endl; // The AT function provides a range check that throws a Out_of_range exception when it crosses the border. cout<<s1[]<<endl; // the subscript operator [] does not provide check access.
Iv. Description of characteristics
1. Determine if it is empty
S1.empty ()
2. Length
string s1="12345678";
cout<<s1.length () <<endl; // . Length () and. Size () No difference, whichever is OK
Cout<<s1.size () <<endl; // size () means that it is a container, and length () indicates that it is a string
3. Redefine the length of it (more go to less fill)
strings1="12345678"; cout<<s1<<Endl; cout<<s1.size () <<endl;//. Length () and. Size () No difference, whichever is OKS1.resize (4);//more tocout<<s1<<Endl; cout<<s1.size () <<Endl; S1.resize (6,'x');//do not write a second parameter can also becout<<s1<<Endl; cout<<s1.size () <<endl;
Basic usage of C + + STL string