45、c_str与data()

简介: c_str()返回的指针保证指向一个size()+1长的空间,而且最后一个字符肯定'\0'。而data返回的指针则保证指向一个size()长度的空间,有没有null-terminate不保证,可能有,可能没有,看库的实现了。

c_str()返回的指针保证指向一个size()+1长的空间,而且最后一个字符肯定'\0'。而data返回的指针则保证指向一个size()长度的空间,有没有null-terminate不保证,可能有,可能没有,看库的实现了。

c_str()返回的是C风格的字符串的首地址,而data()返回的是字符数组的首地址。

    程序中,只在需要时才使用c_str()或者data()得到字符串,每调用一次,下次再使用就会失效。【3

1、const char* c_str ( ) const;

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.

2、const char* data() const;

Returns a pointer to an array of characters with the same content as the string.

Notice that no terminating null character is appended

3、一般,我们需要字符串转换时用c_str(),处理二进制数据时用data()

1http://topic.csdn.net/u/20070120/01/d74734b8-04a7-4ab9-bab8-2ab875b608df.html

2http://blog.csdn.net/feelang/article/details/6338757

3http://www.cnblogs.com/lancidie/archive/2011/03/17/1987130.html

4cplus官网

目录
相关文章
|
3月前
|
JSON 数据格式 Python
TypeError the JSON object must be str, bytes or bytearray, not ‘list‘
TypeError the JSON object must be str, bytes or bytearray, not ‘list‘
【C/C++ strlen(str)和str.length()和str.size()的区别】
strlenQ(str)和str.length()和str.size()都可以求字符串长度,返回字符串中字符的长度,不包括0'。其中str.length()和str.size()是同义词,返回同样的值。
【C/C++ strlen(str)和str.length()和str.size()的区别】
|
安全
string null和“”的区别 str == null; "".equals(str); str.length 0; str.isEmpty();的区别
string null和“”的区别 str == null; "".equals(str); str.length 0; str.isEmpty();的区别
96 0
|
存储
TypeError: can only concatenate str (not “int“) to str
TypeError: can only concatenate str (not “int“) to str
304 0
TypeError: can only concatenate str (not “int“) to str
|
JSON 数据格式 Python
python编程:json indent can't multiply sequence by non-int of type 'str'
python编程:json indent can't multiply sequence by non-int of type 'str'
109 0
成功解决ret = ret / rcountTypeError: unsupported operand type(s) for /: ‘str‘ and ‘int‘
成功解决ret = ret / rcountTypeError: unsupported operand type(s) for /: ‘str‘ and ‘int‘
成功解决ret = ret / rcountTypeError: unsupported operand type(s) for /: ‘str‘ and ‘int‘
How to judge if one model data is out of date
Created by Wang, Jerry, last modified on Jan 12, 2015
84 0
How to judge if one model data is out of date
|
C语言 C++
C++中的 c_str() 函数
功能:c_str() 函数可以将 const string* 类型 转化为 cons char* 类型 头文件:#include<cstring> c_str()就是将C++的string转化为C的字符串数组,c_str()生成一个const char *指针,指向字符串的首地址 因为在c语言中没有string类型,必须通过string类对象的成员函数 c_str() 把 string 转换成c中的字符串样式
C++中的 c_str() 函数