Conversion of String, char *, char[] in C + +
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 str = "Hello"; 2 const char* P = str.data ();//Plus const or char * p= (char*) str.data (); form
At the same time there is a need to explain, here in devc++ compiler need to add const, otherwise will error invalid conversion from the const char* to char *, here can be preceded by a const or after the equal sign to the forced conversion to char* of the type.
The following explanation of the problem, the const char* can not be directly assigned to the char*, so that the compilation can not pass, the reason: if possible, then through the char* will be able to modify the const char point to the content, which is not allowed. So char* to open up a new space, the above form.
2.c_str () method, such as:
1 string str= "World"; 2 const char *p = STR.C_STR ();//ditto, add const or equal to the right with char*
3.copy () method, such as:
1 string str= "Hmmm"; 2 char p[50];3 str.copy (p, 5, 0);//Here 5 is a copy of several characters, 0 represents the location of the copy, 4 * (p+5) = ' + ';//note manual plus Terminator!!!
Second, char * turn string.
You can assign values directly.
1 string s;2 char *p = "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 string pp = "Dagah"; 2 char p[8];3 int i;4 for (I=0;i<pp.length (); i++) 5 p[i] = pp[i];6 p[i ] = ' + '; 7 printf ("%s\n", p); 8 cout<<p;
Iv. char[] Turn string
You can assign values directly here.
Char a[] = "ABC";
std::string B = std::string (a);
Conversion of String, char *, char[] in C + +