FormatReplace Extenssion Method

imageSee code, you see what it is for ;). I did it because .NET had not this kind of method…

using System;
using System.Text;
namespace FormatReplaceSandbox
{
  class Program
  {
    static void Main(string[] args) {
      Console.WriteLine(
        "Ala ma kota, a kot ma Ale"
        .FormatReplace("ma k{0}a, a k{1} m", "ocur", "ocur"));
      Console.WriteLine(
        "Ala ma kota, a kot ma Ale"
        .FormatReplace("Ala ma {0}, a {1} ma Ale", "psa", "pies"));
      Console.WriteLine(
        "Ala ma kota, a kot ma Ale"
        .FormatReplace("{0} ma kota, a kot ma {1}", "Patrycja", "Patrycję"));
      Console.ReadKey(true);
    }
  }
  public static class FormatReplaceHelper
  {
    public static string FormatReplace(
      this string text, string format, params object[] args) {
      int count = 0;
      int partB = 0;
      int length = 0;
      var builder = new StringBuilder();
      for (int i = 0; i < args.Length; ++i) {
        var pPattern = string.Concat("{", count.ToString(), "}");
        var pBegin = format.IndexOf(pPattern, partB);
        var pLength = pPattern.Length;
        var pBeginPart = format.Substring(partB, pBegin - partB);
        var pBeginPartLength = pBeginPart.Length;
        var npPattern = string.Concat("{", (++count).ToString(), "}");
        var npBegin = format.IndexOf(npPattern, partB);
        var pePart =
          npBegin != -1
          ? format.Substring(pBegin + pLength, npBegin - pBegin - pLength)
          : format.Substring(pBegin + pLength, format.Length - pBegin - pLength);
        var paramEndPartLength = pePart.Length;
        var rbIndex = text.IndexOf(pBeginPart, partB);
        if (rbIndex == -1)
          break;
        rbIndex += pBeginPartLength;
        var reIndex = text.IndexOf(pePart, partB);
        if (reIndex == -1)
          break;
        reIndex += paramEndPartLength;
        builder.Append(text.Substring(partB, rbIndex - partB));
        var param = args[i].ToString();
        length = rbIndex + pLength;
        if (length < reIndex)
          length = reIndex;
        builder.Append(param);
        builder.Append(pePart);
        if (npBegin == -1)
          break;
        partB = npBegin;
      }
      if (length < text.Length) {
        builder.Append(text.Substring(length, text.Length - length));
      }
      return builder.ToString();
    }
  }
}

P ;).

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.