C++標準庫的string不是以'\0'結束,而是string類中有一個記錄長度的值
(具體怎麼實現我不是很清楚,要等看過STL代碼或者比我牛的大牛來給你說)
但是C++中的string你要得到它有多長,可以這麼做
string str("abc");
str.size();
str.length(); //都返回3
而且,str中不會以'\0'判斷字符串結束,可以這樣
string str2("\0\0\0\0\0");
str2.size(); //等於5
如果要用string返回一個C style string
那麼可以
str.c_str(); //會在字符串內容後加上一個C style string 的結束符號'\0' 這裏返回的就是 "abc\0"
str.data(); //這裏返回的是 "abc"
嗯,我錯了,但是我在看書的時候怎麼是這麼寫的
我找找看
C++ Standard Library : A tutorial and Reference
中11.1章
Unlike C-strings, objects of
class
string have no special character
'\0' at the end of the
string.
Note that only the single-argument version
char* handles the character
'\0'
as a special character that terminates the
string. In all other cases
'\0'
is not a special character:
std::string s1("nico");
//initializes s1 with: 'n' 'i' 'c' 'o'
std::string s2("nico",5)
; //initializes s2 with: 'n' 'i' 'c' 'o' '\0'
std::string s3(5,'\0');
//initializes s3 with: '\0' '\0' '\0' '\0' '\0'
s1.length() //yields 4
s2.length() //yields 5
s3.length() //yields 5
噢~~~ 是我錯了,想這樣初始化就對了~
std::string s3(5,'\0');
這樣s3 就是 "\0\0\0\0\0"
我那樣初始化的確是錯的,而且我大概知道錯在哪裏了~ 想想看~
想好了再跟個貼
- C/C++ code
-
嗯,錯在初始化方法相關
string str("\0\0\0");
這裏調用的是 string(const char* p) 這個構造函數
這個構造函數的實現應該是依賴C style string的,我大概用自己的想法描述下
string::string(const char* p)
{
/*
將string內部的char* mp申請一個p指向的C風格字符串的長度的空間
將p的內容COPY到mp中
那麼在第一步的時候就使用C風格字符串的判斷長度方法,判斷這個"\0\0\0"的長度是0
- - 所以這樣的初始化得不到我想要的結果
*/
}
而 string(int count,char ch) 則能得到想要表達STL的string不把'\0'做特殊字符處理的意思