Conversion of String, char *, char[] in C + +

Source: Internet
Author: User

The first time someone asked me this question, but I do not have a clue, directly said no. Now from the Internet to find some information, looked at, know something.

One, the string to turn char*.

There are three main ways to convert str to char* type: data (); C_str (); Copy ();

1.data () method, such as:

1 string " Hello " ; 2 char* p = str.data ();

2.c_str () method, such as:

1 string str="World"; 2 char *p = Str.c_str ();

3.copy () method, such as:

1 string str="hmmm"; 2 Char p[]; 3 5 0); // here 5 means to copy a few characters, 0 for the location of the copy 4 * (p+5) ="+"; // Note the manual plus Terminator!!! 

Second, char * turn string.

You can assign values directly.

1 string s; 2 Char " Hello "; // Direct Assignment 3 s = p;

One thing to note here is that when the string type variable s is declared, it is used with printf ("%s", s); The error occurs because "%s" requires the first address of the object that follows. But string is not such a type. So it must be wrong.

Iii. string Transfer char[]

This is because we know the length of the string, can be obtained according to length () function, and can be directly accessed according to subscript, so we can assign a value with a loop.

1     stringPP ="Dagah";2     Charp[8];3     inti;4      for(i=0; I<pp.length (); i++)5P[i] =Pp[i];6P[i] =' /';7printf"%s\n", p);8cout<<p;

Iv. char[] Turn string

You can assign values directly here.

Conversion of String, char *, char[] in C + +

Related Article

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.