Linear Mode

Registered User

Join Date

Aug 2007

Posts

183

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:

Code:

string str = "Hello,\0 world!";
str.erase(str.length() + 1, 1);

Can anyone help? Thanks.

Share this post on

Captain Crash

Join Date

Mar 2007

Location

Portland, OR

Posts

7,314

Originally Posted by mikeman118

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:

Code:

string str = "Hello,\0 world!";
str.erase(str.length() + 1, 1);

Can anyone help? Thanks.

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.

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:

Code:

Share this post on

"Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
-Christopher Hitchens

One way to force the issue would be to manipulate the string as a container;

Code:

std::string str("Hello");
str.append('\0');
str.append(" World");

To find the '\0' character, find() can be used.

Share this post on

Registered User

Join Date

Jan 2002

Location

Northern Virginia/Washington DC Metropolitan Area

Posts

3,806

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.

Share this post on

"Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
-Christopher Hitchens