在字符串中间插入'\ 0'无效(C++)

Avi*_*esh -2 c++ string

我有一个字符串并尝试在第k个位置插入'\ 0'(其中k <n&n是字符串的长度).在第3个位置插入'\ 0'并尝试显示字符串.我得到整个字符串,但我只期望'\ 0'之前的部分?我对吗 ?或者c ++字符串有什么特别之处吗?

比如说:

// My string is as below

string s = "wabcdddeefff"; 

// After inserting '\0' in the 3rd position and tried displaying the string showed the entire string unchanged.
// Will the string now become s = "wab" ??
Run Code Online (Sandbox Code Playgroud)

更清楚.我发布了我的代码.

string s="wwwwaaadexxxxxx";
int l = s.size();
int k = 1;
char a = s[0];
int count = 1;

for(int i=1; i<l; i++)  {
    if(s[i] == a)   {
        count++;    // cout << "\nS["<<i<<"] " << s[i] << " Count " << count;
    }
    else    {
        if(count == 1)  {
            s[k++] = s[i];
        }
        else    {
            s[k++] = count+'0';     //cout << "\n     s["<<k<<"] " << s[k-1] << "count " << count;
            s[k++] = s[i];
        }
        a = s[i];
        count = 1;       //cout << "\nCount " << count << " a " << a;
    }

}  


if(count > 1)
    s[k++] = count+'0';

s[k++] = '\0';
cout << "\n \n String "  << s << endl;
Run Code Online (Sandbox Code Playgroud)

FYU,我已经附加了控制台屏幕截图:)

在此输入图像描述

Lig*_*ica 6

你假设C++ std::string的工作就像空终止的C字符串一样.

他们没有.

C++ std::string是长度感知容器char,通常是二进制安全的.这意味着你可以char在其中存储任意s而不会破坏任何东西.这非常有用,因为现在您可以在Unicode表示中存储任意数据,包括可能在更高抽象级别的字符串.或者数据可以是二进制编码的信息.

你可以std::string以你期望的方式"打破"a的唯一方法是获得指向底层缓冲区的指针(即a const char*,via std::string::c_str())并将其视为C字符串,必要时,它被认为是空终止的您可能会使用的所有C库函数,包括负责输出的函数.

你试图在这里实现的那种逻辑是一个C语言,利用了C字符串的限制.当您使用现代"容器"时,它不会逐字翻译成C++.1

如果你想截断a std::string,只需调用std::string::resize它上面的成员函数:

s.resize(k);
Run Code Online (Sandbox Code Playgroud)

你以后会感谢我的.

1从技术上讲,std::string标准库用语不是容器.但是,从一般意义上说,它是包含其他东西的东西,所以...