Search code examples
c++std

The std::string is able to stores multiple '\0'. How to trim it?


As in the title, the example below shows that the std::string is able to store multiple string termination characters. How to trim the string so the size() and length() reflects its actual length i.e. the c-string length. Is there a built in method?

#include <iostream>
#include <string>

int main(int argc, char **argv)
{
    std::string s;
    s = "abc";
    s[1] = '\0';
    
    std::cout << "'" << s << "', " << s.size() << ", " << (int) s[1];
}

Solution

  • If you have access to C++20 or higher then there is a built in function for this: std::erase

    With this you can can remove all nested null characters like

    std::erase(my_string, '\0');
    

    This works because the final '\0' that ends the string lives at end and that is outside the range that erase will use since erase uses [begin(), end())


    If you want to remove everything after the first '\0' then you can use

    my_string.erase(std::find(my_string.begin(), my_string.end(), '\0'), my_string.end());