Basic usage of C + + STL string

Source: Internet
Author: User

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

Contact Us

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

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.