As an alternative, and perhaps an overkill, here's a StrTran which uses Regex
using System;
using GregoryAdam.Base.ExtensionMethods;
namespace BaseTest
{
class test3
{
static void Main()
{
string[,] test =
{
{ "hello", "o", "123", "hell123"},
{ "+1+2", "+", "-", "-1-2" },
{ "$1$2", "$", "-", "-1-2" },
{ "{1+{2", "{", "-", "-1+-2" },
{ "{1+{2", "{", "$", "$1+$2" },
{ "hello", "O", "$$", "hell$$"},
{ "hello", "H", @"$1\$2", @"$1\$2ello"},
{ "hello", "H", null, @"ello"}
};
for (int i = 0; i <= test.GetUpperBound(0); i++)
{
string input = test[i, 0];
string from = test[i, 1];
string to = test[i, 2];
string expect = test[i, 3];
string got = input.Replace(from, to, true);
Console.WriteLine("input: {0}, expect: {1}, got: {2}, result: {3}", input, expect, got, expect == got);
}
Console.ReadLine();
}
}
}
using System;
using System.Text;
using System.Text.RegularExpressions;
using GregoryAdam.Base.Constants;
namespace GregoryAdam.Base.ExtensionMethods
{
public static partial class ExtensionMethods_String
{
public static string Replace(
this string s,
string oldValue,
string newValue,
bool ignoreCase
)
{
if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(oldValue))
return s;
string oldValuePattern = Regex.Replace(
oldValue,
RegexConstants.SpecialPatternCharsPattern,
RegexConstants.SpecialPatternCharsPatternReplace
);
string newValuePattern;
if (string.IsNullOrEmpty(newValue))
newValuePattern = "";
else
newValuePattern = Regex.Replace(
newValue,
RegexConstants.SpecialReplaceCharsPattern,
RegexConstants.SpecialReplaceCharsPatternReplace
);
RegexOptions regexOptions = !ignoreCase?
RegexOptions.None
: RegexOptions.CultureInvariant | RegexOptions.IgnoreCase;
return Regex.Replace(s, oldValuePattern, newValuePattern, regexOptions);
}
}
}
using System.Text;
namespace GregoryAdam.Base.Constants
{
public static class RegexConstants
{
public static readonly char[] SpecialPatternChars =
{ '\\', '^', '$', '.',
};
public static readonly string SpecialPatternCharsPattern =
Build_SpecialPatternCharsPattern(SpecialPatternChars);
public static string SpecialPatternCharsPatternReplace = @"\$1";
public static readonly char[] SpecialReplaceChars =
{ '$' };
public static readonly string SpecialReplaceCharsPattern =
Build_SpecialPatternCharsPattern(SpecialReplaceChars);
public static readonly string SpecialReplaceCharsPatternReplace = @"$$$1";
private static string Build_SpecialPatternCharsPattern(char[] chars)
{
StringBuilder sb = new StringBuilder(chars.Length * 3 + 1);
sb.Append('(');
foreach (char c in chars)
{
sb.AppendFormat(@"\{0}|", c);
}
sb[sb.Length-1] = ')';
return sb.ToString();
}
}
}
Gregory