看下面的英文解釋:
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()字符串后有'\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* 相關處理也就清晰了。
相關參考資料:
http://www.metsky.com/archives/582.html
http://oss.org.cn/html/32/n-3732.html
