简体   繁体   中英

Remove ASCII Character 28 From string array

I have written code which reads network stream and stores data into byte array, then convert that byte array to string array.

I want to remove non printable ASCII character (Code 28 ie File Separator) from string array or directly from byte array.

How can I achieve the same ?

I tried following code:

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

Code :-

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

Not sure about the byte array but from the string you can use string.Replace. If its a single string:

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

For array:

saBytesReceived = saBytesReceived.Select(s => s.Replace(((char)28).ToString(), "")).ToArray();

This was annoying me after converting a HEX string to UTF8 string because then I couldn't seem to remove the empty values from the array. @Habib you char cast and to string did the trick. 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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM