zoukankan      html  css  js  c++  java
  • c++ string c_str() 和data()区别

    看下面的英文解释:

    const char* c_str ( ) const;
    Get C string equivalent
    Generates a null-terminated sequence of characters (c-string) with the same content as the string object and returns it as a pointer to an array of characters.
    A terminating null character is automatically appended.

    const char* data() const;
    Get string data
    Returns a pointer to an array of characters with the same content as the string.
    Notice that no terminating null character is appended (see member c_str for such a functionality).

    第一点:c_str()字符串后有'',而data()没有。
    第二点: data 返回的数组(虽然是char* 但是和  c_str 还是有本质区别的)-----data 能解决一个问题 string 串中 包含 情况的问题。结合size 方法就能随意访问返回的数据了.  注意他返回的是array 数组.

    中间带结束符的string对象

    有多种方法可实现中间带结束符的string对象初始化。但是像:

    string s="123  123";
    s5="abc";
    s5+="def";

    这样的初始化方法都是不行的,因为编译器或运行时默认都会截掉结束符后面的字符串。结果就是:

    s="123 "

    s5="abcdef"

    1、构造法初始化

    string s5= string("12345  54321", 13);
    

    这样的方式初始化,这时 s5="12345 54321"

    2、append函数添加

    除了上面方法,还可以使用append函数,代码如下:

    s5.append("abc",4);
    s5.append("def",4);

    知道怎么构造,知道怎么解析,string char* 相关处理也就清晰了。


    相关参考资料:
      http://www.metsky.com/archives/582.html 

      http://oss.org.cn/html/32/n-3732.html

  • 相关阅读:
    Linux Shell 01 脚本与变量
    Linux下shell颜色配置
    Linux下Redis安装及配置
    Linux Shell 03 条件测试
    OSX下VirtualBox安装CentOS
    Log4j配置与使用
    Linux 环境变量的配置
    OS X下安装Redis及配置开机启动
    圈复杂度
    (转)Qt Model/View 学习笔记 (一)——Qt Model/View模式简介
  • 原文地址:https://www.cnblogs.com/porter/p/3830190.html
Copyright © 2011-2022 走看看