c++ string c_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.
Notice that no terminating null character is appended (see member c_str for such a functionality).

第一点:c_str()字符串后有'',而data()没有。
第二点: data 返回的数组(虽然是char* 但是和  c_str 还是有本质区别的)-----data 能解决一个问题 string 串中 包含 情况的问题。结合size 方法就能随意访问返回的数据了.  注意他返回的是array 数组.

中间带结束符的string对象

有多种方法可实现中间带结束符的string对象初始化。但是像:

string s="123  123";
s5="abc";
s5+="def";

这样的初始化方法都是不行的,因为编译器或运行时默认都会截掉结束符后面的字符串。结果就是:

s="123 "

s5="abcdef"

1、构造法初始化

string s5= string("12345  54321", 13);

这样的方式初始化,这时 s5="12345 54321"

2、append函数添加

除了上面方法,还可以使用append函数,代码如下:

s5.append("abc",4);
s5.append("def",4);

知道怎么构造,知道怎么解析,string char* 相关处理也就清晰了。


相关参考资料:
  http://www.metsky.com/archives/582.html 

  http://oss.org.cn/html/32/n-3732.html

原文地址:https://www.cnblogs.com/porter/p/3830190.html