c-style 字符串 与 C++ 的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。想理解这个问题需要一点背景知识:

  1. 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;

中的参数CharT为char时的特例。

  1. s.size()会返回std::string中字符的个数,即:
string s{'a', 'b', '\0', 'c'};
cout << s.size() << endl;  // 输出 4
s += '\0';
s += 'd';
cout << s.size() << endl;  // 输出 6
  1. 使用[]运算符(即std::basic_string::reference std::basic_string::operator[](size_type pos);)获取std::string中的字符时,其字符的范围pos是从0到size()。其中0到size()-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::string是char,且char()返回的是\000,所以s[s.size()]会返回\0。

  2. 通过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[s.size()],所以会发现返回值是\0。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 【转载】原文地址:std::string详解作者:kieven2008 之所以抛弃char*的字符串而选用C++标...
    VAYY阅读 661评论 0 2
  • 本文转自:http://www.cnblogs.com/lidabo/p/5225868.html 1)字符串操作...
    XiaohuiLI阅读 9,562评论 0 0
  • 一、字符串操作 strcpy(p, p1) 复制字符串 strncpy(p, p1, n) 复制指定长度字符串 s...
    JaiUnChat阅读 1,675评论 0 7
  • 在c语言中,字符串是用字符数组来存储的(并不像c++或者java等语言中有单独的string类型), 存放时在字符...
    朱森阅读 1,599评论 0 2
  • 1.ascertain V-T If you ascertain the truth about somethin...
    邱天阅读 393评论 0 0