从字符串数组中删除ASCII字符28

时间:2013-01-02 10:10:41

标签: c# string ascii

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

我想从字符串数组中删除不可打印的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();
            }
         }
      }
   }
}

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:0)

将HEX字符串转换为UTF8字符串后,这让我很烦,因为我似乎无法从数组中删除空值。 @Habib你的char演员和字符串做了伎俩。 TY。

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;
    }