C + + String and its comparison with char[]

Source: Internet
Author: User

Before I learned C + +, I usually learned the language.

In the C language we save the string using char[]

But the use of string is more frequent in C + + than char[] The following is a little bit of my understanding of string

1. As with other standard library types, a user program needs to use a string type object to contain the associated header file (to provide an appropriate using declaration for easy authoring)

#include <string>using std::string;

Definition and initialization of 2.string objects

    string s1;//Creating an empty    string  string s2 ("wo yao ac");//create strings with an initial value of wo yao    ac s2string S3 (S2);//Create S2 copy   s3 Value change  does not affect S2    string S4 (2,'A  ');//Create a String S4   value of 2 characters ' a    'string s5=s2+s3;//Create a string S5   value of S2+S3

The output result is

3.string Reading and writing

In c we use the following two methods to read into the string

scanf ("%s", S1);
Gets (S1);

In C + +, the read-in method used for string-type data is CIN

cin>>s1;

Reading and ignoring the beginning of the whitespace character reads the string to resemble scanf ("%s", S1) until it encounters a white-space character again;

But when it comes to solving the problem, we can't just save contiguous non-empty characters.

At this time we need a reading method like Get (Getline) (CIN,S1);

Operation of 4.string objects

    S1.empty ();   // to determine if S1   is null is to return true   not to return false    s2.size ();    // returns the number    of characters in S2 S1[i];   // returns the character    that is labeled I in S1 S1+S2;  // returns a string  whose value is equal to S1 followed by S2    s1=s2;   // pay the value of S2 to S1

C + + String and its comparison with char[]

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.