>// string >namespace GregoryAdam.Base.ExtensionMethods >{ > public static partial class ExtensionMethods > { >#region ChrTran > public static string ChrTran(this string s, string from, string to) > { > // check parameters > if( String.IsNullOrEmpty(s) ) > return s; > > if( String.IsNullOrEmpty(from) ) > return s; > > > // (1) Split from into translate and remove > > // "1234", "56" > // translate = "12" > // remove = "34" > char[] translate, remove; > > // "1234", "" > if (String.IsNullOrEmpty(to)) > { > translate = new char[0]; > > } > // "1234", "5678" > // "1234", "56" > // "1234", "A" > // "1234", "567890" - can happen > else > { > translate = new char[Math.Min(from.Length, to.Length)]; > from.CopyTo(0, translate, 0, translate.Length); > } > > remove = new char[from.Length - translate.Length]; > from.CopyTo(translate.Length, remove, 0, remove.Length); > > // (2) remove chars from s - but not those that will be translated > // avoid StrTran("AA", "B") > // translate = "A", to = "B" > // remove = "A" > var sb = new StringBuilder(s, s.Length); > int i, j; > > for (i = remove.Length; --i >= 0; ) > { > if( !translate.Contains( remove[i] ) ) > sb.Replace(remove[i].ToString(), null); > } > > // (3) translate > > // if no char in from is in to, then a fast translate can be done > // if not, we'll have to loop > > if (translate.Length > 0) > { > bool fastTranslate = true; > > for (i = translate.Length; --i >= 0; ) > { > if (to.Contains(from[i])) > { > fastTranslate = false; > break; > } > } > > if (fastTranslate) > { > for (i = translate.Length; --i >= 0; ) > { > sb.Replace(translate[i], to[i]); > } > } > else > { > for (i = sb.Length; --i >= 0; ) > { > if ((j = Array.IndexOf<char>(translate, sb[i])) >= 0) > sb[i] = to[j]; > } > } > } > return sb.ToString(); > } >#if ChrTran_TESTSUITE > static string[,] chrtranTest = > { { "AB", "AB", "BC", "BC" } , > { "AB", "AB", "B", "B" }, > { "0123456", "45", null, "01236"}, > { "0123456", "456", "78", "012378"}, > { "01234567890", "456", "", "01237890"}, > { "02468", "02468", "1357", "1357"}, > { "02468", "02468", "1358", "1358" } > }; > > public static void chrtran_Test() > { > string s; > > for (int i = -1; ++i <= chrtranTest.GetUpperBound(0); ) > { > s = chrtranTest[i, 0].ChrTran(chrtranTest[i, 1], chrtranTest[i, 2]); > > Console.WriteLine("{0},{1},{2} >> {3} {4} : {5}", > chrtranTest[i, 0], > chrtranTest[i, 1], > chrtranTest[i, 2], > chrtranTest[i, 3], > s, > s == chrtranTest[i, 3] > ); > } > } >#endif >#endregion > > } >} >