C++ string类不能像C字符串能靠在i位赋值为‘\0’来截断

来源:互联网 发布:指南针软件是不是骗局 编辑:程序博客网 时间:2024/05/16 19:39

C++ string类不能像C字符串能靠在i位赋值为‘\0’来截断,因为'\0'在C字符串中才具有字符结束符的意义

#include <string>

#include <map>
#include <iostream>

using namespace std;

int main()
{
    string s("abcdefg");

    s[3] = '\0';

cout << s.size() << endl;

    cout << s << endl;
    cout << s.c_str() << endl;
    char ss[10]={"abcdefg"};
    ss[3] = '\0';
    cout << ss << endl;
    cout << string(ss) << endl;
    return 0;

}


得结果为:

7
abcefg
abc
abc
abc