Note that there are some explanatory texts on larger screens.

plurals
  1. POremove chars from string in c++
    primarykey
    data
    text
    <p>I was implementing a method to remove certain characters from a string txt, <strong>in-place</strong>. the following is my code. The result is expected as "bdeg". however the result is "bdegfg", which seems the null terminator is not set. the weird thing is that when I use gdb to debug, after setting null terminator </p> <pre><code>(gdb) p txt $5 = (std::string &amp;) @0xbffff248: {static npos = &lt;optimized out&gt;, _M_dataplus = {&lt;std::allocator&lt;char&gt;&gt; = {&lt;__gnu_cxx::new_allocator&lt;char&gt;&gt; = {&lt;No data fields&gt;}, &lt;No data fields&gt;}, _M_p = 0x804b014 "bdeg"}} </code></pre> <p>it looks right to me. So what is the problem here?</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; using namespace std; void censorString(string &amp;txt, string rem) { // create look-up table bool lut[256]={false}; for (int i=0; i&lt;rem.size(); i++) { lut[rem[i]] = true; } int i=0; int j=0; // iterate txt to remove chars for (i=0, j=0; i&lt;txt.size(); i++) { if (!lut[txt[i]]){ txt[j]=txt[i]; j++; } } // set null-terminator txt[j]='\0'; } int main(){ string txt="abcdefg"; censorString(txt, "acf"); // expect: "bdeg" std::cout &lt;&lt; txt &lt;&lt;endl; } </code></pre> <p><strong>follow-up question</strong>:</p> <p>if string is not truncated like c string. so what happens with <code>txt[j]='\0'</code> and why it is "bdegfg" not 'bdeg'\0'g' or some corrupted strings.</p> <p><strong>another follow-up</strong>: if I use <code>txt.erase(txt.begin()+j, txt.end()</code>); it works fine. so I'd better use string related api. the point is that I do not know the time complexity of the underlying code of these api. </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload