Conversion between cstring, String, char *

Source: Internet
Author: User

It is often used in the past few days.

Each of these three types has its own advantages. For example, cstring is flexible. It is a common type based on MFC and has the highest security, but has the worst portability. String is an essential type when STL is used, so it must be mastered during Engineering. char * is inseparable from us since learning C language, many APIs use char * as the parameter input. Therefore, it is necessary to master the conversion between the three.

Below I will use a simple illustration to point out the relationship between the three and use the label-based conversion method.

 

1 string to cstring

Cstring. Format ("% s", String. c_str ());

2 cstring to string

String STR (cstring. getbuffer (Str. getlength ()));

3 string to char *

Char * P = string. c_str ();

4 char * to string

String STR (char *);

5 cstring to char *

Strcpy (char, cstring, sizeof (char ));

6 char * To cstring

Cstring. Format ("% s", char *);

the format method of cstring is very useful. C_str () of string is also very common, but it is the safest to define char as const char * during conversion 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.