Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Null-terminated String ใน C/C++ คืออะไร?

Null-terminated string (C-string) คือ array of characters ที่จบด้วย null character '\0' (ASCII 0)

ลักษณะสำคัญ

  • ใน C: string คือ char[] หรือ char* ที่จบด้วย '\0'
  • ใน C++: std::string จัดการความยาวเอง (ไม่ต้องใช้ null terminator ภายใน) แต่ c_str() คืน null-terminated string
  • Compiler แปลง string literal "hello" เป็น {'h','e','l','l','o','\0'} อัตโนมัติ
  • ขนาด array อาจใหญ่กว่าความยาว string แต่ '\0' แรกคือจุดสิ้นสุด

ตัวอย่าง

string s = "This is a sample text";
cout << s; // This is a sample text

s = "This is a sam\0ple text"; // มี \0 กลาง string
cout << s; // This is a sam (std::string เก็บ '\0' เป็นส่วนหนึ่งของข้อมูลได้ แต่ c_str() จะตัดที่นี่)

ผลลัพธ์

This is a sample text
This is a sam

ฟังก์ชัน C string (strlen, strcpy, strcmp) ทั้งหมดทำงานโดยหา '\0' เป็นสัญญาณจบ