C++ std::string和 C-style string区别

C++ 中的std::string和 C-style string 是两种不同的字符串,前者是标准库中定义的一个类,后者是字符数组的别名。

  • C-style string:通常都以\0作为结尾。

  • std::string:标准中未规定需要\0作为字符串结尾。编译器在实现时既可以在结尾加\0,也可以不加。但是,当通过c_str()data()(二者在 C++11 及以后是等价的)来把std::string转换为const char *时,会发现最后一个字符是\0(原因见文末附录)。

C-style string 中一般不能包含\0字符(因为这个字符被当作表示字符串结束的特殊字符处理了),如果包含这个字符,那么其后的字符将会被忽略。即:

char s[] = "ab\0c";
cout << s << endl;  // 输出 ab

std::string没有这个限制。即:

std::string s{'a', 'b', '\0', 'c'};
//std::string s = "ab\0c";  // 这里由于是从 C-style string 构造 std::string,所以仍然会忽略 \0 之后的字符
cout << s << endl;  // 输出 ab c
附录

通过c_str()data()(二者在 C++11 及以后是等价的)来把std::string转换为const char *时,会发现最后一个字符是\0。想理解这个问题需要一点背景知识:

一,std::string 是 std::basic_string<CharT, Traits, Allocator>这个模板的特例std::basic_string<char>。即模板:

template< 
    class CharT, 
    class Traits = std::char_traits<CharT>, 
    class Allocator = std::allocator<CharT>
> class basic_string;

中的参数CharTchar时的特例。

二,s.size()会返回std::string中字符的个数,即:

string s{'a', 'b', '\0', 'c'};
cout << s.size() << endl;  // 输出 4
s += '\0';
s += 'd';
cout << s.size() << endl;  // 输出 6

三,使用[]运算符(即std::basic_string::reference std::basic_string::operator[](size_type pos);)获取std::string中的字符时,其字符的范围pos是从0size()。其中0size()-1是所存储的字符,而对于pos == size()有如下规定:

If pos == size(), a reference to the character with value CharT() (the null character) is returned. For the first (non-const) version, the behavior is undefined if this character is modified.

意思是当访问s[s.size()]时,会返回CharT()的返回值的引用,而CharT对于std::stringchar,且char()返回的是\000,所以s[s.size()]会返回\0

四,通过c_str()data()const CharT* c_str() const;)返回的指针访问字符串时,其效果为:

Returns: A pointer p such that p + i == &operator[](i) for each i in [0,size()].

p[s.size()]等价于p + s.size()等价于&s.operator[](s.size())等价于s[s.size()],所以会发现返回值是\0

转载于:https://my.oschina.net/wdyoschina/blog/1490635

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值