gpt4 book ai didi

c++ - 字符串长度函数 w.r.t 空字符的奇怪行为?

转载 作者:行者123 更新时间:2023-11-30 00:37:57 31 4
gpt4 key购买 nike

我有这段代码说:

 std::string str("ashish");  
str.append("\0\0");
printf("%d", str.length());

它正在打印 6 但如果我有这段代码

 std::string str("ashish");  
str.append("\0\0",2);
printf("%d", str.length());

正在打印 8 !为什么?

最佳答案

是因为str.append("\0\0")使用空字符来判断字符串的结尾。所以“\0\0”的长度为零。另一个重载,str.append("\0\0",2),只占用你给它的长度,所以它附加了两个字符。

来自标准:

  basic_string&
append(const charT* s, size_type n);

7         Requires: s points to an array of at least n elements of charT.

8         Throws: length_error if size() + n > max_size().

9         Effects: The function replaces the string controlled by *this with a string of length size() + n whose first size() elements are a copy of the original string controlled by *this and whose remaining elements are a copy of the initial n elements of s.

10         Returns: *this.

  basic_string& append(const charT* s);

11         Requires: s points to an array of at least traits::length(s) + 1 elements of charT.

12         Effects: Calls append(s, traits::length(s)).

13         Returns: *this.

                                                               — [string::append] 21.4.6.2 p7-13

关于c++ - 字符串长度函数 w.r.t 空字符的奇怪行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12285060/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com