什么是C / C ++中以null终止的字符串?
在C语言中,字符串基本上是字符数组。在C++中,std::string是该数组的改进。传统字符数组还有一些其他功能。空终止的字符串基本上是一个字符序列,最后一个元素是一个空字符(由“\0”表示)。当我们使用双引号(“...”)编写某些字符串时,编译器会将其转换为以空终止的字符串。
字符串的大小可能小于数组的大小,但是如果该数组中有一些空字符,则将其视为该字符串的结尾。
请参见以下示例。在这里,我们使用std::string定义了一个字符串,然后我们将提供相同的字符串,但是其中会有一个\0。
示例
#include<iostream> using namespace std; main() { string my_string = "This is a sample text"; cout << my_string << endl; my_string = "This is a sam\0ple text"; //check the \0 cout << my_string; }
输出结果
This is a sample text This is a sam