Replace Unprintable Characters - CSharp System

CSharp examples for System:String Replace

Description

Replace Unprintable Characters

Demo Code

//  The contents of this file are subject to the Common Public Attribution License Version 1.0 (the ?License?); 
using System.Globalization;
using System.Text.RegularExpressions;
using System.Text;
using System.Collections.Generic;
using System;/*from   w  ww.  java 2s  .  com*/

public class Main{
        public static string ReplaceUnprintableCharacters( string stringIn, string replacement )
		{
			if ( string.IsNullOrEmpty( stringIn ) )
			{
				return stringIn;
			}

			//The range of printable characters are the characters with ASCII code 32-126
			//build a regex string the contains all of the characters concatinated together
			StringBuilder sbValidCharacters = new StringBuilder();
			for ( int idx = 32; idx <= 126; idx++ )
			{
				sbValidCharacters.Append( (char)idx );
			}

			//Include newlines, carraige returns and tabs in the characters that we want to keep
			sbValidCharacters.Append( '\n' ).Append( '\r' ).Append( '\t' );

			//Build the regex as the set of characters NOT in the set that we want to keep
			Regex regExp = new Regex( "[^" + sbValidCharacters.ToString() + "]{1}" );


			//Replace the characters that are not valid with string.Empty
			return regExp.Replace( stringIn, string.Empty );

		}
}

Related Tutorials