奇怪的行为的字符串长度函数w.r.t null字符? [英] Strange behaviour of string length function w.r.t null character?

查看:127
本文介绍了奇怪的行为的字符串长度函数w.r.t null字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码说:

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

正在打印6,但如果我有此代码

It is printing 6 but if I have this code

 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),只需要你给它的长度,所以它追加两个字符。

It's because str.append("\0\0") uses the null character to determine the end of the string. So "\0\0" is length zero. The other overload, str.append("\0\0",2), just takes the length you give it, so it appends two characters.

从标准:


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

7         : s 指向至少 n 的元素的数组 charT

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

8      size()+ n> max_size()。

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

9      >该函数用 * this 替换长度为 size()+ n 的字符串,其第一个 size()元素是由 * this 控制的原始字符串的副本,其余元素是初始 n 的元素。

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         返回: * this

10         Returns: *this.

  basic_string& append(const charT* s);

11         : c> c>指向一个至少 traits :: length(s)+ 1 元素的数组 charT

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

12        效果:调用 append(s,traits :: length)

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

;        返回: * this

13         Returns: *this.

                          ;                          ;                — [string :: append] 21.4.6.2 p7-13

                                                               — [string::append] 21.4.6.2 p7-13

这篇关于奇怪的行为的字符串长度函数w.r.t null字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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