C++ 插入'\0';在字符串的中间没有任何效果(C&A X2B;

C++ 插入'\0';在字符串的中间没有任何效果(C&A X2B;,c++,string,C++,String,我有一个字符串,并尝试在第k个位置插入“\0”(其中k 比如说: // 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" ?? 更清楚地说。

我有一个字符串,并尝试在第k个位置插入“\0”(其中k 比如说:

// 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" ??
更清楚地说。我已经发布了我的代码

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;
string s=“wwaaadexxxxxx”;
int l=s.size();
int k=1;
字符a=s[0];
整数计数=1;

对于(int i=1;i
std::string
不需要空终止符,请使用C strings
const char*
获得所需的输出


<>或用 CyString()//COD>打印字符串。

< P>假定C++ >代码> STD::String < /Cult>的工作就像空终止的C字符串。

他们没有

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

以您期望的方式“断开”一个
std::string
的唯一方法是获取一个指向底层缓冲区的指针(即通过
std::string::c_str()
)的
const char*
)并将其视为一个C字符串,根据需要,所有可能使用的C库函数(包括那些负责输出的函数)都认为该字符串以null结尾

你在这里尝试实现的逻辑是C语言,它利用C字符串的限制。当你使用现代的容器时,它不会逐字翻译成C++。1 如果要截断
std::string
,只需调用其上的成员函数
std::string::resize

s.resize(k);
以后你会为此感谢我的


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

Okie!!但是我可以使用string本身实现我的目标吗???@SteveJobs使用
yourstring.c_str()打印出来不幸的是,Jamey已经把你送错了方向。不幸的是,你把C给了错的方向。你开始用C类C++,现在它更像C++。@ Lexness CraceSeNeReString只回答了这个问题。为什么不写一些代码,在代码的中间插入“代码>”\ 0’< /CUD>?史蒂夫:没问题,祝贺你的复活。