Sometimes you may need to display or print an input string that contains binary characters.  The following function replaces all binary characters in a string with a blank.  You can easily modify this method to remove other undesirable characters (such as high-ASCII) if needed.

Strip Function

static public string CleanString( string s )
{
    if (s != null && s.Length > 0)
    {
        StringBuilder sb = new StringBuilder( s.Length );
        foreach (char c in s)
        {
            sb.Append( Char.IsControl( c ) ? ' ' : c );
        }
        s = sb.ToString();
    }
    return s;
}

Sample Console Program

Here is a simple console program that demonstrates this:

using System;
using System.Text; 

namespace CSharp411
{
    class Program
    {
        static void Main( string[] args )
        {
            Random r = new Random();
            int length = 1000;
            StringBuilder sb = new StringBuilder( length );
            for (int i = 0; i < length; i++)
            {
                sb.Append( (char)r.Next( 255 ) );
            }
            string s = sb.ToString();
            s = CleanString( s );
            Console.WriteLine( s );
            Console.ReadLine();
        }
        static public string CleanString( string s )
        {
            if (s != null && s.Length > 0)
            {
                StringBuilder sb = new StringBuilder( s.Length );
                foreach (char c in s)
                {
                    sb.Append( Char.IsControl( c ) ? ' ' : c );
                }
                s = sb.ToString();
            }
            return s;
        }
    }
}
Share and Enjoy:
  • Digg
  • Twitter
  • Facebook
  • Reddit
  • StumbleUpon
  • LinkedIn
  • Google Bookmarks
  • Slashdot