using System; using System.Collections.Generic; using System.Linq; using System.Text; public class Test { public static void Main() { var input = "one two four"; var replace = new Dictionary() { { "one", "two" }, { "two", "three" }, }; Console.WriteLine(ReplaceOnce(input, replace)); } static string ReplaceOnce(string input, IDictionary replacements) { var processedCharCount = 0; var sb = new StringBuilder(); while (processedCharCount < input.Length) { var replacement = replacements.Select(r => new { Term = r.Key, Index = input.IndexOf(r.Key, processedCharCount)}) .Where(p => p.Index != -1) .OrderBy(p => p.Index).ThenByDescending(p => p.Term.Length) .FirstOrDefault(); if (replacement == null) { break; } sb.Append(input, processedCharCount, replacement.Index - processedCharCount); sb.Append(replacements[replacement.Term]); processedCharCount = replacement.Index + replacement.Term.Length; } sb.Append(input.Substring(processedCharCount)); return sb.ToString(); } }