Conversion Between the string type and common data types

Source: Internet
Author: User

1. String-> cstring

CString cs;string s("abc");cs.Format("%s",s.c_str());

2. String-> const char *

string s("abc");const char* c = s.c_str();

The c_str () function returns a regular pointer to a string in the C format. c ++ primer says, assigning the address of a const object to a normal, non-const object pointer will lead to compilation errors, but the non-const object address can be assigned to the pointer pointing to the const object. Therefore, the left operator must be a pointer to the const object.

3. String-> char *

 string source = "abcdefg"; int length = strlen(source.c_str()); char *s = new char[length+1]; memset(s,0,length+1); strcpy(s,source.c_str()); cout << s << endl; delete []s;

In this case, the memory is dynamically allocated.

4. String-> char []

string source = "abcdefg";char charArray[10];memset(charArray,0,10);strcpy(charArray,source.c_str());cout<<charArray<<endl;

5. String-> int

string source = "12";int a = atoi(source.c_str());cout << a <<endl;

6. Char buffer [row]-> string

char buffer[10] = {"abcdefg"};string source(buffer);cout << source << endl;

7. Char buffer [row] [line]-> string

char buffer[2][10] = {"abcd","asdf"};char buf[20];strcpy(buf,buffer[0]);strcat(buf,buffer[1]);string source(buf);cout << source << endl;

8. INT (float...)-> string

char buffer[20];int  i = 3445;   itoa( i, buffer, 10 );string s(buffer);cout<< s << endl;

char buffer[20];int  i = 3445;sprintf(buffer,"%d",i);string s(buffer);cout << s << endl;

 

// Stringstream () header file <sstream. h> int I = 3445; stringstream SS; SS <I; string S = ss. STR (); cout <S <Endl;

9. cstring-> string

Cstring STR; string buffer (STR); // or cstring STR; string STR (Str. getbuffer (); Str. releasebuffer ();

10. Char-> string

char c = 'a';string s(1,c);cout << s << endl;

11. char *-> string

char* ss = "abddas";string s(ss);cout << s << endl;

12. Char []-> string

char a[] = "adfadsf";string s(a);cout << s << endl;

 

 

 

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.