1

我编写了读取网络流并将数据存储到字节数组中的代码,然后将该字节数组转换为字符串数组。

我想从字符串数组或直接从字节数组中删除不可打印的 ASCII 字符(代码 28 即文件分隔符)。

我怎样才能达到同样的效果?

我尝试了以下代码:

saBytesReceived = saBytesReceived.Select(s => s.Replace(@"[^U+001C]", "")).ToArray();

代码 :-

if (serverSocket.Connected)
{
   bBytesToRead = serverSocket.Available;

   if (bBytesToRead > 0)
   {
      try
      {
         bDataReceived = new byte[bBytesToRead];
         networkStream.Read(bDataReceived, 0, bBytesToRead);
         try
         {
            if (System.Text.ASCIIEncoding.ASCII.GetString(bDataReceived).Trim() != "")
            {
               uncompletedMessage.IdleCount = 0;                                            
               saBytesReceived = System.Text.ASCIIEncoding.ASCII.GetString(bDataReceived).Split(new string[] { "\n" }, StringSplitOptions.None);
               saBytesReceived = saBytesReceived.Select(s => s.Replace(@"[^U+001C]", "")).ToArray();
            }
         }
      }
   }
}
4

2 回答 2

5

不确定字节数组,但可以从字符串中使用 string.Replace。如果它是一个字符串:

string str = "1" + (char)(28) + "2";
//str.Length == 3
str = str.Replace(((char)28).ToString(), "");
//str.Length == 2

对于数组:

saBytesReceived = saBytesReceived.Select(s => s.Replace(((char)28).ToString(), "")).ToArray();
于 2013-01-02T10:21:53.360 回答
0

在将 HEX 字符串转换为 UTF8 字符串后,这让我很恼火,因为那时我似乎无法从数组中删除空值。@Habib 你 char cast 和 to string 成功了。泰。

public static string GetString( string hex )
    {
        byte[ ] raw = new byte[ hex.Length / 2 ];
        for( int i = 0; i < raw.Length; i++ )
        {
            byte convertToByte = Convert.ToByte( hex.Substring( i * 2, 2 ), 16 );
            raw[ i ] = convertToByte;
        }

        var result = Encoding.UTF8.GetString( raw ).Replace( ( ( char ) 0 ).ToString( ), "" );

        return result;
    }
于 2013-11-27T18:19:35.480 回答