c++stringc_str()和data()区别
看下⾯的英⽂解释:
const char* c_str ( ) const;
Get C string equivalent
Generates a null-terminated sequence of characters (c-string) with the same content as the string object and returns it as a pointer to an array of characters.
A terminating null character is automatically appended.
const char* data() const;
Get string data
Returns a pointer to an array of characters with the same content as the string.
c++中string的用法Notice that no terminating null character is appended (see member c_str for such a functionality).
第⼀点:c_str()字符串后有'\0',⽽data()没有。
第⼆点: data 返回的数组(虽然是char* 但是和  c_str 还是有本质区别的)-----data 能解决⼀个问题 string 串中包含 \0 情况的问题。结合size ⽅法就能随意访问返回的数据了.  注意他返回的是array 数组.
中间带\0结束符的string对象
有多种⽅法可实现中间带结束符\0的string对象初始化。但是像:
string s="123 \0 123";
s5="abc\0";
s5+="def\0";
这样的初始化⽅法都是不⾏的,因为编译器或运⾏时默认都会截掉结束符后⾯的字符串。结果就是:
s="123 "
s5="abcdef"
1、构造法初始化
string s5= string("12345 \0 54321", 13);
这样的⽅式初始化,这时 s5="12345 \0 54321"
2、append函数添加
除了上⾯⽅法,还可以使⽤append函数,代码如下:
s5.append("abc\0",4);
s5.append("def\0",4);
知道怎么构造,知道怎么解析,string char* 相关处理也就清晰了。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。