Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help with \0 terminated strings in C#

Tags:

string

c#

cstring

I'm using a low level native API where I send an unsafe byte buffer pointer to get a c-string value.

So it gives me

// using byte[255] c_str
string s = new string(Encoding.ASCII.GetChars(c_str));

// now s == "heresastring\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0(etc)";

So obviously I'm not doing it right, how I get rid of the excess?

like image 707
y2k Avatar asked Apr 05 '10 21:04

y2k


People also ask

Does C automatically null terminate strings?

char arrays are not automatically NULL terminated, only string literals, e.g. char *myArr = "string literal"; , and some string char pointers returned from stdlib string methods. C does no bounds checking.

What is the reason C string terminates with the \0 character?

C strings are null-terminated. That is, they are terminated by the null character, NUL . They are not terminated by the null pointer NULL , which is a completely different kind of value with a completely different purpose. NUL is guaranteed to have the integer value zero.

How do you null-terminated strings?

The null character indicates the end of the string. Such strings are called null-terminated strings. The null terminator of a multibyte string consists of one byte whose value is 0. The null terminator of a wide-character string consists of one gl_wchar_t character whose value is 0.

What is the purpose of '\ 0 character in C?

\0 is zero character. In C it is mostly used to indicate the termination of a character string.


2 Answers

There may be an option to strip NULs in the conversion.

Beyond that, you could probably clean it up with:

s = s.Trim('\0');

...or, if you think there may be non-NUL characters after some NULs, this may be safer:

int pos = s.IndexOf('\0');  
if (pos >= 0)
    s = s.Substring(0, pos);
like image 32
Jason Williams Avatar answered Oct 20 '22 23:10

Jason Williams


.NET strings are not null-terminated (as you may have guessed from this). So, you can treat the '\0' as you would treat any normal character. Normal string manipulation will fix things for you. Here are some (but not all) options.

s = s.Trim('\0');

s = s.Replace("\0", "");

var strings =  s.Split(new char[] {'\0'}, StringSplitOptions.RemoveEmptyEntries);

If you definitely want to throw away any values after the first null character, this might work better for you. But be careful, it only works on strings that actually include the null character.

s = s.Substring(0, Math.Max(0, s.IndexOf('\0')));
like image 51
John Fisher Avatar answered Oct 20 '22 23:10

John Fisher