|
在.NET中字符串替换的五种方法(1) 1:使用String.Replace函数替换,但不支持大小写。 2:正则System.Text.Regex 替换,用RegEXPOption修改是否支持大小写。 3:在小数据的情况下,使用String.SubString 和+可以实现间接替换。 4:导入Microsoft Visual Basic RunTime (Microsoft.VisualBasic.DLL) 使用Strings.Replace速度很快。 5:参照反射Reflector.FileDisassembler配合Strings.Split and Strings.Join 等实现,速度同5。
一下介绍一种算法,类似KMP算法。有兴趣的参照研究下。
private static string ReplaceEx(string original, string pattern, string replacement) { int count, position0, position1; count = position0 = position1 = 0; string upperString = original.ToUpper(); string upperPattern = pattern.ToUpper(); int inc = (original.Length/pattern.Length) * (replacement.Length-pattern.Length); char [] chars = new char[original.Length + Math.Max(0, inc)]; while( (position1 = upperString.IndexOf(upperPattern, position0)) != -1 ) { for ( int i=position0 ; i < position1 ; ++i ) chars[count++] = original[i];
|