DigitTransformer.cs 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System.Text;
  2. namespace Day1;
  3. public class DigitTransformer
  4. {
  5. private static readonly Dictionary<string, string> _digits = new Dictionary<string, string>
  6. {
  7. ["one"] = "1",
  8. ["two"] = "2",
  9. ["three"] = "3",
  10. ["four"] = "4",
  11. ["five"] = "5",
  12. ["six"] = "6",
  13. ["seven"] = "7",
  14. ["eight"] = "8",
  15. ["nine"] = "9",
  16. };
  17. public string Replace(string input)
  18. {
  19. var result = new StringBuilder();
  20. for (var i = 0; i < input.Length; i++)
  21. {
  22. var current = input.Substring(i);
  23. var next = false;
  24. foreach (var kvp in _digits)
  25. {
  26. if (current.StartsWith(kvp.Key))
  27. {
  28. result.Append(kvp.Value);
  29. next = true;
  30. break;
  31. }
  32. }
  33. if (!next)
  34. {
  35. result.Append(current[0]);
  36. }
  37. }
  38. return result.ToString();
  39. }
  40. }