我在 C 中遇到字串和空字符的問題。當我在字串之間寫入 '\0' 并列印字串時,我只得到 '\0' 之前的部分,但另一方面,當我將字串作為輸入然后將任何索引更改為 '\0' 然后它列印方式不同。為什么是這樣,為什么在這兩種情況下 sizeof(string) 都是 32 代碼如下供參考。請幫忙。
第一個代碼:
#include<iostream>
using namespace std;
int main(){
string s = "he\0llo";
cout<<s.length()<<"\n";
cout<<s<<endl;
cout<<sizeof(s)<<"\n";
}
第一個代碼的輸出:
2\n
he\n
32\n
第二個代碼
#include<iostream>
using namespace std;
int main(){
string s;
cin>>s;
s[1] = '\0';
cout<<s<<"\n";
cout<<s.length()<<"\n";
cout<<sizeof(s)<<"\n";
return 0;
}
第二個代碼的輸出:
hllo\n
5\n
32\n
下面是圖片供您參考。

uj5u.com熱心網友回復:
std::string的隱式const CharT*建構式和賦值運算子不知道字串引數的確切長度。相反,它只知道這是 aconst char*并被迫假設字串將以空終止,因此使用std::char_traits::length(...)(有效地std::strlen)計算長度。
因此,構造一個std::string具有如下運算式的物件:
std::string s = "he\0llo";
將計算2為字串的長度,因為它假定第一個\0字符是字串的空終止符,而您的第二個示例是:
s[1] = '\0';
只是在已經構造的字串中添加一個空字符——這不會改變字串的大小。
如果你想構造一個中間有空字符的字串,你不能讓它為你計算字串的長度。相反,您必須以std::string其他方式構造并為其指定長度。這可以通過string(const char*, size_t)建構式完成,或者如果這是一個陣列,則使用迭代器對:
// Specify the length manually
std::string s{"he\0llo",6};
Live Example
// Using iterators to a different container (such as an array)
const char c_str[] = "he\0llo";
std::string s{std::begin(c_str), std::end(c_str)};
Live Example
注意: sizeof(s)告訴您std::string類本身的大小(以位元組為單位),用于標準庫的實作。這不會告訴您包含的字串的長度 - 可以從s.length()或確定s.size()。
uj5u.com熱心網友回復:
從 c 14 開始,有一個選項可以使用 std::literals 將帶引號的字串指定為 std::string。這可以防止將字符陣列轉換為字串,而字串會在第一個空字符處自動停止。
#include<iostream>
#include <string>
using namespace std;
using namespace std::literals;
int main() {
string s = "he\0llo"s; // This initializes s to the full 6 char sequence.
cout << s.length() << "\n";
cout << s << endl;
cout << sizeof(s) << "\n"; // prints size of the s object, not the size of its contents
}
結果:
6
hello
28
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/343574.html
上一篇:在Rust中構建新字串的有效方法
下一篇:第一個重復字符|運行
