Mar 18
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; } } }
I test this function but not working.
many binary correcter still there.
Nido, see this webpage for the list of “control” characters that are removed:
http://msdn.microsoft.com/en-us/library/18zw7440.aspx
As I mentioned in the article, the sample code does not remove high ASCII or UNICODE characters which may appear as binary. Run the sample code on your data, and see what binary characters still remain. Then add a check to the loop to remove those characters as well.
I have solved my problem with adding two line of code
The new funciton will be…
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);
if(Char.IsSymbol(c))
{
continue;
}
sb.Append(Char.IsLetterOrDigit(c) ? c : ‘ ‘);
}
s = sb.ToString();
}
return s;
}
Thanks for sharing such nice function
this is really useful, thx