我想測試一下,如果字符串追加char的大小,下面是結果。字符串追加char changning其大小
我知道字符串以空字符結尾,但爲什麼結果是這樣?
#include <iostream>
#include <string>
using namespace std;
int main(){
string a = "" + 'a'; //3
string b = "" + '1'; //2
string c = "a" + 'a'; //2
string d = "1" + '1'; //3
string e = "\0" + 'a'; //20
string f = "\0" + '1'; //1
string g = "a" + '\0'; //1
string h = "1" + '\0'; //1
string i = "" + '\0'; //0
string j = "" + '\0'; //0
cout << a.size() << endl;
cout << b.size() << endl;
cout << c.size() << endl;
cout << d.size() << endl;
cout << e.size() << endl;
cout << f.size() << endl;
cout << g.size() << endl;
cout << h.size() << endl;
cout << i.size() << endl;
cout << j.size() << endl;
return 0;
}
爲什麼string(「a」)+'\ 0'size是2 //我認爲它應該是1 ,,,, string(「\ 0」)+'a'size是1 //我認爲它應該是0 ,,,, string(「」)+'\ 0'size is 1 //我認爲應該是0 ,,,,, String'size不應該計算空字符? –
'std :: string'是一個*計數的字符串*,即它的長度存儲在一個單獨的字段中,而'\ 0'字符不作爲字符串分隔符 - 它是一個普通字符。它在字符串中的存在不會改變字符串的長度。 –
Thx提前回復。 –