【面试题】String类型中间可以包含'\0'吗

答案是可以的,Test:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    char *cStr = "hello\0world";
    string str{'a', 'b', '\0', 'c'};
    string str1("world\0hello");
    unsigned char b = 255;
    printf("cStr = %s  str = %s  str1 = %s \n", cStr, str.c_str(), str1.c_str());
    cout << "str: " << str << " str1: " << str1  <<endl;
    cout << "str1.size = " << str1.size() << endl;
    cout << "str.size = " << str.size() << endl;
    system("pause");
    return 0;
}

结果如下:


之所以str1并未包含‘\0’,是因为他是C风格的字符串常量,而C串是以'\0'作为结束标志符,所以str1的初始化等价于=》str1("world")。

c语言用char*指针作为字符串时,在读取字符串时需要一个特殊字符0来标记指针的结束位置,也就是通常认为的字符串结束标记。

而c++语言则是面向对象的,长度信息直接被存储在了对象的成员中,读取字符串可以直接根据这个长度来读取,所以就没必要需要结束标记了。

参考:

c++ 自带string类 的对象 字符串结尾带不带‘\0’?

猜你喜欢

转载自blog.csdn.net/u010275850/article/details/79841919