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<string, string>()
{
{ "one", "two" },
{ "two", "three" },
};
Console.WriteLine(ReplaceOnce(input, replace));
}
static string ReplaceOnce(string input, IDictionary<string, string> 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();
}
}
dXNpbmcgU3lzdGVtOwp1c2luZyBTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYzsKdXNpbmcgU3lzdGVtLkxpbnE7CnVzaW5nIFN5c3RlbS5UZXh0OwoKcHVibGljIGNsYXNzIFRlc3QKewoJcHVibGljIHN0YXRpYyB2b2lkIE1haW4oKQoJewogICAgICAgIHZhciBpbnB1dCA9ICJvbmUgdHdvIGZvdXIiOwogICAgICAgIHZhciByZXBsYWNlID0gbmV3IERpY3Rpb25hcnk8c3RyaW5nLCBzdHJpbmc+KCkKICAgICAgICB7CiAgICAgICAgICAgIHsgIm9uZSIsICJ0d28iIH0sCiAgICAgICAgICAgIHsgInR3byIsICJ0aHJlZSIgfSwKICAgICAgICB9OwogICAgCQogICAgCUNvbnNvbGUuV3JpdGVMaW5lKFJlcGxhY2VPbmNlKGlucHV0LCByZXBsYWNlKSk7Cgl9CiAgICAKICAgIHN0YXRpYyBzdHJpbmcgUmVwbGFjZU9uY2Uoc3RyaW5nIGlucHV0LCBJRGljdGlvbmFyeTxzdHJpbmcsIHN0cmluZz4gcmVwbGFjZW1lbnRzKQogICAgewogICAgICAgIHZhciBwc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