为什么在 std 字符串中间设置 null 没有任何效果 [英] Why setting null in the middle of std string doesn't have any effect

查看:35
本文介绍了为什么在 std 字符串中间设置 null 没有任何效果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑

#include <string>
#include <iostream>

int main()
{
    /*
    hello
    5
    hel
    3
    */
    char a[] = "hello";
    std::cout << a << std::endl;
    std::cout << strlen(a) << std::endl;
    a[3] = 0;
    std::cout << a << std::endl;
    std::cout << strlen(a) << std::endl;

    /*
    hello
    5
    hel o
    5
    */
    std::string b = "hello";
    std::cout << b << std::endl;
    std::cout << b.length() << std::endl;
    b[3] = 0;
    std::cout << b << std::endl;
    std::cout << b.length() << std::endl;

    getchar();

}

我希望 std::string 的行为与 char 数组 a 相同.就是这样,在字符串中间插入空字符,将终止"字符串.然而,事实并非如此.我的期望错了吗?

I expect std::string will behave identical to char array a. That's it, insert null character in the middle of the string, will "terminate" the string. However, it is not the case. Is my expectation wrong?

推荐答案

std::string 不像通常的 C 字符串,可以毫无问题地包含嵌入的 NUL 字符.但是,如果您这样做,您会注意到如果您使用 .c_str() 函数返回一个 const char *,字符串会提前终止.

A std::string is not like a usual C string, and can contain embedded NUL characters without problems. However, if you do this you will notice the string is prematurely terminated if you use the .c_str() function to return a const char *.

这篇关于为什么在 std 字符串中间设置 null 没有任何效果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆