String from byte array doesn't get trimmed in C#?

后端 未结 5 1741
南笙
南笙 2020-12-18 18:40

I have a byte array similar to this (16 bytes):

71 77 65 72 74 79 00 00 00 00 00 00 00 00 00 00

I use this to convert it to a string and tr

相关标签:
5条回答
  • 2020-12-18 18:52

    Trim by default removes only whitespace, where whitespace is defined by char.IsWhitespace.

    '\0' is a control character, not whitespace.

    You can specify which characters to trim using the Trim(char[]) overload:

    string result = Encoding.ASCII.GetString(data).Trim(new char[] { '\0' });
    
    0 讨论(0)
  • 2020-12-18 18:57

    Why try to create the string first and trim it second? This could add a lot of overhead (if the byte[] is large).

    You can specify index and count in the GetString(byte[] bytes, int index, int count) overload.

    int count = data.Count(bt => bt != 0); // find the first null
    string result = Encoding.ASCII.GetString(data, 0, count); // Get only the characters you want
    
    0 讨论(0)
  • 2020-12-18 19:04

    They're not really spaces:

    System.Text.Encoding.ASCII.GetString(byteArray).TrimEnd('\0')
    

    ...should do the trick.

    -Oisin

    0 讨论(0)
  • 2020-12-18 19:05

    You have to do TrimEnd(new char[] { (char)0 }); to fix this. It's not spaces - it's actually null characters that are converted weirdly. I had this issue too.

    0 讨论(0)
  • 2020-12-18 19:11

    In powershell, you can do this:

    $yourString.TrimEnd(0x00)
    
    0 讨论(0)
提交回复
热议问题