The main problem with what you have is that it traverses the string at least
n
(the number of strings to replace) times (if none of the strings are found), and perhaps as many as
2n
times (if all of the strings are found). This can be reduced to
n
times simply by removing the
if
s.
But it's a task that really doesn't require more than one traversal of the string. The following method builds a
RegularExpression
that searches for the strings you want to replace, looks for matches, then constructs a new string if there were matches.
somestring.RegexReplace
(
new System.Collections.Generic.Dictionary<string,string>()
{
{ "'" , "'" }
,
{ " " , "<" }
...
}
) ;
Because the strings be searched for are used in a RegularExpression, this technique is more powerful, but will require careful attention to the values provided.
public static string
RegexReplace
(
this string Subject
,
System.Collections.Generic.Dictionary<string,string> Replacement
)
{
if ( !System.String.IsNullOrEmpty ( Subject ) && ( Replacement != null ) && ( Replacement.Count > 0 ) )
{
System.Text.StringBuilder workarea =
new System.Text.StringBuilder ( Subject.Length ) ;
foreach ( string s in Replacement.Keys )
{
workarea.AppendFormat ( "({0})|" , s ) ;
}
workarea.Length-- ;
System.Text.RegularExpressions.Regex reg =
new System.Text.RegularExpressions.Regex ( workarea.ToString() ) ;
System.Text.RegularExpressions.MatchCollection mat =
reg.Matches ( Subject ) ;
if ( mat.Count > 0 )
{
workarea.Length = 0 ;
int offset = 0 ;
for ( int i = 0 ; i < mat.Count ; i++ )
{
workarea.Append ( Subject.Substring ( offset , mat [ i ].Index - offset ) ) ;
workarea.Append ( Replacement [ mat [ i ].Value ] ) ;
offset = mat [ i ].Index + mat [ i ].Length ;
}
workarea.Append ( Subject.Substring ( offset ) ) ;
Subject = workarea.ToString() ;
}
}
return ( Subject ) ;
}