Removing null characters from strings
-
If I have a string that has null characters at the end, how can I remove them? Doing Trim('\0') didn't work and I can't think of anything else to try, besides manually finding the position of the last non-null character and then removing everything after it or something like that.
-
If I have a string that has null characters at the end, how can I remove them? Doing Trim('\0') didn't work and I can't think of anything else to try, besides manually finding the position of the last non-null character and then removing everything after it or something like that.
-
If I have a string that has null characters at the end, how can I remove them? Doing Trim('\0') didn't work and I can't think of anything else to try, besides manually finding the position of the last non-null character and then removing everything after it or something like that.
-
Trim trims spaces not anything else. If you want to trim other chars you need to use the Trim( new char[]{' ', '\0'} ); or what ever you need. TrimEnd( new char[]{' ', '\0'} ); TrimStart( new char[]{' ', '\0'} );
-
string str; byte [] charStr = new byte[] {(byte)'T', (byte)'e', (byte)'s', (byte)'t', 0, 0, 0, 0, 0, 0}; str = Encoding.ASCII.GetString(charStr); // str now contains "Test\0\0\0\0\0\0"; str = str.TrimEnd(new char[]{'\0'}); // str now contains "Test"
This code works. Make sure you are assigning the return value of TrimEnd method to your string. It does not actually trim the contents of string object but rather generates a new trimmed string. -
string str; byte [] charStr = new byte[] {(byte)'T', (byte)'e', (byte)'s', (byte)'t', 0, 0, 0, 0, 0, 0}; str = Encoding.ASCII.GetString(charStr); // str now contains "Test\0\0\0\0\0\0"; str = str.TrimEnd(new char[]{'\0'}); // str now contains "Test"
This code works. Make sure you are assigning the return value of TrimEnd method to your string. It does not actually trim the contents of string object but rather generates a new trimmed string.After looking at docs, this is even better:
str = str.TrimEnd('\0');
Also, if you are reading a null terminated string, there is a chance you have garbage characters after the terminating null. This will prevent Trim methods from working. So, your best approach would be:int Index = str.IndexOf('\0'); if (Index >= 0) str = str.Substring(0, Index);