如何将std::string转换为char*或const char*?


当前回答

我正在使用一个API,其中有很多函数获得char*作为输入。

我创建了一个小类来处理这类问题,并且实现了RAII习惯用法。

class DeepString
{
        DeepString(const DeepString& other);
        DeepString& operator=(const DeepString& other);
        char* internal_; 
    
    public:
        explicit DeepString( const string& toCopy): 
            internal_(new char[toCopy.size()+1]) 
        {
            strcpy(internal_,toCopy.c_str());
        }
        ~DeepString() { delete[] internal_; }
        char* str() const { return internal_; }
        const char* c_str()  const { return internal_; }
};

你可以这样使用它:

void aFunctionAPI(char* input);

//  other stuff

aFunctionAPI("Foo"); //this call is not safe. if the function modified the 
                     //literal string the program will crash
std::string myFoo("Foo");
aFunctionAPI(myFoo.c_str()); //this is not compiling
aFunctionAPI(const_cast<char*>(myFoo.c_str())); //this is not safe std::string 
                                                //implement reference counting and 
                                                //it may change the value of other
                                                //strings as well.
DeepString myDeepFoo(myFoo);
aFunctionAPI(myFoo.str()); //this is fine

我将这个类称为DeepString,因为它正在创建一个现有字符串的深度且唯一的副本(DeepString不可复制)。

其他回答

从c++ std字符串转换到c风格字符串现在真的很容易。

为此,我们有string::copy函数,它可以轻松地将std字符串转换为C风格字符串。参考

字符串::连续复制函数形参

Char字符串指针 字符串大小,b复制多少个字符 位置,从字符复制开始的位置

另一件重要的事,

此函数不会在操作结束时附加空字符。所以,我们需要手动放置它。

代码考试在下面

// char string
char chText[20];

// c++ string
string text =  "I am a Programmer";

// conversion from c++ string to char string
// this function does not append a null character at the end of operation
text.copy(chText, text.size(), 0);

// we need to put it manually
chText[text.size()] = '\0';

// below statement prints "I am a Programmer"
cout << chText << endl;

反之亦然,从C样式字符串转换到c++ std字符串要容易得多

有三种方法可以将C样式字符串转换为c++ std字符串

第一个是使用构造函数,

char chText[20] = "I am a Programmer";
// using constructor
string text(chText);

第二个是使用string::assign方法

// char string
char chText[20] = "I am a Programmer";

// c++ string
string text;

// convertion from char string to c++ string
// using assign function
text.assign(chText);

第三个是赋值操作符(=),其中字符串类使用操作符重载

// char string
char chText[20] = "I am a Programmer";

// c++ string
// convertion from char string to c++ string using assignment operator overloading
string text = chText;

第三个也可以写成如下-

// char string
char chText[20] = "I am a Programmer";

// c++ string
string text;


// convertion from char string to c++ string
text = chText;

如果你只是想将std::string传递给一个需要const char *的函数,你可以使用.c_str():

std::string str;
const char * c = str.c_str();

如果你需要一个非const char *,调用.data():

std::string str;
char * c = str.data();

.data()是在c++ 17中添加的。在此之前,你可以使用&str[0]。

注意,如果std::string是const, .data()将返回const char *,就像.c_str()一样。

如果字符串被销毁或重新分配内存,指针将失效。

指针指向一个以空结束的字符串,终止符不计入str.size()。不允许将非空字符分配给结束符。

看看这个:

string str1("stackoverflow");
const char * str2 = str1.c_str();

但是,请注意,这将返回一个const char *。

对于char *,使用strcpy将其复制到另一个char数组中。

我正在使用一个API,其中有很多函数获得char*作为输入。

我创建了一个小类来处理这类问题,并且实现了RAII习惯用法。

class DeepString
{
        DeepString(const DeepString& other);
        DeepString& operator=(const DeepString& other);
        char* internal_; 
    
    public:
        explicit DeepString( const string& toCopy): 
            internal_(new char[toCopy.size()+1]) 
        {
            strcpy(internal_,toCopy.c_str());
        }
        ~DeepString() { delete[] internal_; }
        char* str() const { return internal_; }
        const char* c_str()  const { return internal_; }
};

你可以这样使用它:

void aFunctionAPI(char* input);

//  other stuff

aFunctionAPI("Foo"); //this call is not safe. if the function modified the 
                     //literal string the program will crash
std::string myFoo("Foo");
aFunctionAPI(myFoo.c_str()); //this is not compiling
aFunctionAPI(const_cast<char*>(myFoo.c_str())); //this is not safe std::string 
                                                //implement reference counting and 
                                                //it may change the value of other
                                                //strings as well.
DeepString myDeepFoo(myFoo);
aFunctionAPI(myFoo.str()); //this is fine

我将这个类称为DeepString,因为它正在创建一个现有字符串的深度且唯一的副本(DeepString不可复制)。

比方说, 字符串str =“堆栈”;

1)将字符串转换为char*

  char* s_rw=&str[0]; 

上面的字符*(即。, s_rw)是可读可写的,并且指向基 需要转换为char*的字符串的地址

2)将字符串转换为const char*

   const char* s_r=&str[0];

上面的const char*(即s_r)是可读的但不可写的,并且指向 字符串的基址。