2013-01-02 96 views
1

我已經編寫了讀取網絡流並將數據存儲到字節數組中的代碼,然後將該字節數組轉換爲字符串數組。刪除ASCII字符28從字符串數組

我想從字符串數組或直接從字節數組中刪除不可打印的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(); 
      } 
     } 
     } 
    } 
} 

回答

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(); 
0

這是討厭我一個十六進制字符串轉換爲UTF8字符串後,因爲那時我似乎無法從數組取出空值。 @哈比布你演員和絃都做了伎倆。 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; 
    }