zoukankan      html  css  js  c++  java
  • string

    • std::string length() and size() member functions.
      As per the documentation, these are just synonyms.

    • Error: invalid operands of types ‘const char [35]’ and ‘const char [2]’ to binary ‘operator+’

    std::string str = "Hello " + "world"; // bad!
    std::string str = std::string("Hello ") + "there " + "world"; // ok
    
    const char *st = "hello";
    // 赋值转换 
    string st1 = st;
    // 构造转换 
    string s1(st, st + strlen(st));
    
    // string转char *
    string st = "My test";
    //char *st1 = st;           // 错误类型不同 
    //char *st1 = st.c_str();   // 错误类型不同, const char* c_str() const; st对象被析构时,其内容将丢失!
    char *st1 = const_cast<char *>(st.c_str()) ;
    

    const char c_str();
    c_str()函数返回一个指向正规C字符串的指针, 内容与本string串相同.
    这是为了与c语言兼容,在c语言中没有string类型,故必须通过string类对象的成员函数c_str()把string 对象转换成c中的字符串样式。
    注意:一定要使用strcpy()函数 等来操作方法c_str()返回的指针
    比如:最好不要这样:
    char
    c;
    string s="1234";
    c = s.c_str(); //c最后指向的内容是垃圾,因为s对象被析构,其内容被处理

    应该这样用:
    char c[20];
    string s="1234";
    strcpy(c,s.c_str());
    这样才不会出错,c_str()返回的是一个临时指针,不能对其进行操作

    data()与c_str()

    data只是返回原始数据序列,没有保证会用traits::eos(),或者说''来作字符串结束.
    当然,可能多数实现都这样做了。

    c_str是标准的做法,返回的char* 一定指向一个合法的用''终止的C兼容的字符串。
    所以,如果需要C兼容的字符串,c_str 是标准的做法,data 并不保证所有STL的实现的一致性。

  • 相关阅读:
    hibernate 注解text,大文本类型
    ARRAYLIST VECTOR LINKEDLIST 区别与用法(转载)
    Javascript 异步加载详解
    浏览器是怎样工作的(二):渲染引擎,HTML解析
    浏览器是怎样工作的(一):基础知识
    ajax和json
    30+ CSS Grid System
    写好高效CSS的定律
    960网页栅格化总结
    响应式网站之测试工具
  • 原文地址:https://www.cnblogs.com/friedCoder/p/12942487.html
Copyright © 2011-2022 走看看