【C/C++】C 与 C++ 字符串操作

C字符串是使用 null 字符 ‘\0’ 终止的一维字符数组, C++字符串是一个继承了容器操作的类.

c_str 操作

cpp_str 操作

相互转化

//c_str to cpp_str
char c_str[] = "Hello";
string cpp_str(c_str)

C++字符串有两个内建函数, 可以使用 C 字符串指向数据,

const char *data()const;//返回一个非null终止的c字符数组    
const char *c_str()const;//返回一个以null终止的c字符串  

但是要想构造出一个 C 字符串,必须使用 strcpy 函数

#include <cstring>
// cpp_str to c_str
string cpp_string = "World";
char c_str[] = "";

strcpy(c_str, cpp_string.data());

Ref

猜你喜欢

转载自blog.csdn.net/baishuo8/article/details/82118671