// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Text.RegularExpressions; namespace Eksperten { class Class1 { private const int N = 1000000; public static void Main(string[] args) { string Source = "Det er kun den første forekomst af ordet Alpha som skal erstattes med Beta - ikke den anden forekomst af Alpha. Nemlig, ja!"; Console.WriteLine(Source); string Target = ""; long t1 = DateTime.Now.Ticks; for(int i = 0; i < N; i++) { Target = ReplaceOne1(Source, "Alpha", "Beta"); } long t2 = DateTime.Now.Ticks; Console.WriteLine(Target); Console.WriteLine((t2 - t1) / 10000000.0); long t3 = DateTime.Now.Ticks; for(int i = 0; i < N; i++) { Target = ReplaceOne2(Source, "Alpha", "Beta"); } long t4 = DateTime.Now.Ticks; Console.WriteLine(Target); Console.WriteLine((t4 - t3) / 10000000.0); } public static string ReplaceOne1(string s, string fnd, string rpl) { int ix = s.IndexOf(fnd); if(ix >= 0) { return s.Substring(0, ix) + rpl + s.Substring(ix + fnd.Length); } else { return s; } } public static string ReplaceOne2(string s, string fnd, string rpl) { string OldPattern = string.Format("(.*?){0}(.*)", fnd); string NewPattern = string.Format("$1{0}$2", rpl); Regex RE = new Regex(OldPattern); return RE.Replace(s, NewPattern); } } }