Finding \0 in a string
Like the title states, would anyone know how to find (and remove) a \0 from a std::string? You're probably wondering why that would be in there in the first place, but it doesn't really matter. Let's say we had a string like "Hello \0 world", and I wanted to get rid of the \0 so I could see the whole string. Does anyone have any ideas? I've tried this but it doesn't work:
Can anyone help? Thanks.
string str = "Hello,\0 world!";
str.erase(str.length() + 1, 1);
That initializer won't work, because it is invoked std::string's constructor which takes a C-string. It will stop when it hits the null byte.
Originally Posted by mikeman118
As for how to locate a null byte in a string, just use find(). Then use the resulting index to erase() it.
This might work:
std::string str("Hello\0 World",12);
std::string::size_type pos = str.find('\0');
if( pos != std::string::npos )
I'm not sure offhand if
works for initialising str or not with that embedded '\0'; there's the incidental interaction with the convention that a C-style string stops at the first '\0' character.
std::string str("Hello\0 World", 12);
One way to force the issue would be to manipulate the string as a container;
To find the '\0' character, find() can be used.
I tried it in Visual Studio 2005 and that method of initialization did... something. I was able to find and delete the '\0'. I also printed the string before the deletion and "Hello World" (two spaces) was printed... seems that the '\0' gets converted to a space when output.