【问题标题】:Why setting null in the middle of std string doesn't have any effect为什么在 std 字符串中间设置 null 没有任何效果
【发布时间】:2011-01-11 02:56:57
【问题描述】:

考虑

#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 相同。就是这样,在字符串中间插入空字符,将“终止”字符串。然而,事实并非如此。我的预期错了吗?

【问题讨论】:

    标签: c++ stdstring


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      否 - std::strings 不像 C“字符串”那样以 NUL 结尾; std::string 独立记录其长度。

      【讨论】:

        【解决方案3】:

        @Lou 是对的:不要那样做。而是这样做:

        b.erase (3, b.length());
        

        【讨论】:

          【解决方案4】:

          是的,你的期望是错误的。 std::string 意味着不同于 C 字符串(例如,不一定存储在连续的内存/数组中)。

          要复制第一部分的行为,请尝试使用std::cout &lt;&lt; b.c_str() 而不是std::cout &lt;&lt; b

          【讨论】:

          • 我们不能最终放弃任何人都将使用非连续存储实现string 的理论吗? C++0x 使其符合vector
          • 有了这个评论,你可能会激怒某人实际这样做。
          【解决方案5】:

          我希望 std::string 的行为与 char 数组 a 相同。

          为什么?文档中没有任何内容与 std::string 有任何关系。

          我的建议,不要把 C++ 当作 C 加上一些东西。

          【讨论】:

            猜你喜欢
            • 2018-02-07
            • 1970-01-01
            • 2018-05-27
            • 2015-05-31
            • 2011-05-05
            • 1970-01-01
            • 2015-02-19
            • 2016-09-30
            • 2018-11-16
            相关资源
            最近更新 更多