开发者

C++ String and char * c stype strings

I have a c library which use char arrays as strings and i want t开发者_开发百科o use c++ std::string on my code, could someone help me how can i convert between char * c style strings and STL library strings ?

for example i have :

char *p="abcdef";
string p1;

and

string x="abc";
char *x1;

how can i convert p to p1 and x to x1


Use string's assignment operator to populate it from a char *:

p1 = p;

Use string's c_str() method to return a const char *:

x1 = x.c_str();


From char* to std::string :

char p[7] = "abcdef";
std::string s = p;

From std::string to char* :

std::string s("abcdef");
const char* p = s.c_str();


You can construct a std::string from a C string thus:

string p1 = p;

You can get a const char * from a std::string thus:

const char *x1 = x.c_str();

If you want a char *, you'll need to create a copy of the string:

char *x1 = new char[x.size()+1];
strcpy(x1, x.c_str());
...
delete [] x1;


string has a constructor and an assignment operator that take a char const* as an argument, so:

string p1(p);

or

string p1;
p1 = p;

Should work. The other way around, you can get a char const* (not a char*) from a string using its c_str() method. That is

char const* x1 = x.c_str();


#include <string.h>
#include <stdio.h>

// Removes character pointed to by "pch"
// from whatever string contains it.
void delchr(char* pch)
{
    if (pch)
    {
        for (; *pch; pch++)
            *pch = *(pch+1);
    }
}

void main()
{
    // Original string
    char* msg = "Hello world!";

    // Get pointer to the blank character in the message
    char* pch = strchr(msg, ' ');

    // Delete the blank from the message
    delchr(pch);

    // Print whatever's left: "Helloworld!"
    printf("%s\n", msg);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜