You can operate on strings in C++ both via the string class or the old (i.e. C like) const char pointer.
Notes on string:
To use the class string you have to include the string header:
#include <string>
In addition, to avoid mentioning every time the std namespace, I use the using keyword:
using namespace std;
(without this instruction you'll need to type std::string variable_name instead of just string variable_name)
From char* or char array to string
This is easier
const char *pCh="foo char* "; // pointer to const char
/* two possible conversion methods */
string strTemp(pCh); // through constructor
string strTemp= pCh; // through assignment operator
NOTE:
Since the strong similarity between pointers and arrays, the previous commands work also with char arrays...
char aCh="foo char[] ";
/* two possible conversion methods */
string strTemp(aCh); // through constructor
string strTemp= aCh; // through assignment operator
From string to char*or char array
In this case, the conversion to the const char is very quick, while going to char array takes a bit longer...
string to const char*
string strMyString="This is a string"; // creation of a string object
/* using the c_str() method of the string object*/
const char *pCh=str.MyString.c_str();
string to char array
/ *
In this case, we need:
(1) to assign the correct size of the char array
(2) to copy the string to the char array (char after char or by using strncpy)
(3) a null character to terminate the char array.
*/
string strMyString="This is a string"; // creation of a string object with size = 16!
/* using the size() method of the string object*/
char aCh[str.MyString.size()+1]; // the +1 is for terminating the char array with '\0', size=17!
// copying via the string strncpy...
strncpy(aCh, strMyString.c_str(), strMyString.size()); // SYNTAX: strncpy(destination, source, length)
// ... alternatively we can copy using a for loop:
for (int ii=0; ii<strMyString.size(); ii++)
aCh[ii]=strMyString[ii]; //the loop stops at 15 and that's fine... we have copied 16 characters, since we started from 0!
// either way you use to copy the string, do not forget to add the null terminating character!
aCh[strMyString.size()]='\0'; // at position 16 in the char array
NOTE:
The trickiest part is always to take into account for the correct size of the char array, paying attention to the fact that in C/C++ arrays start at 0, not 1!!!
No comments:
Post a Comment
Your comment will be visible after approval.