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?
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.
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.
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.
\0 is zero character. In C it is mostly used to indicate the termination of a character string.
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);
.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')));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With