Sidneys1

c# Custom string.format and indexOf Implementation

Jun 14th, 2014
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.11 KB | None | 0 0
  1. public static string FormatString(string format, params object[] vars)
  2. {
  3.     List<int>[] lists = new List<int>[vars.Length];
  4.     int lastIndex = 0;
  5.  
  6.     for (int i = 0; i < vars.Length; i++)
  7.     {
  8.         lists[i] = new List<int>();
  9.         int index = -1;
  10.         string current = "{" + i + "}";
  11.         do
  12.         {
  13.             index = format.ctIndexOf(current, lastIndex + 1);
  14.             if (index != -1)
  15.                 lists[i].Add(index);
  16.             lastIndex = index;
  17.         } while (index != -1);
  18.         lastIndex = 0;
  19.     }
  20.  
  21.     for (int i = lists.Length - 1; i >= 0; i--)
  22.     {
  23.         string current = "{" + i + "}";
  24.         for (int j = lists[i].Count - 1; i >= 0; i--)
  25.         {
  26.             int removeAt = lists[i][j];
  27.             format = format.Remove(removeAt, current.Length);
  28.             format = format.Insert(removeAt, vars[i].ToString());
  29.         }
  30.     }
  31.  
  32.     return format;
  33. }
  34.  
  35. public static int ctIndexOf(this string str, string find, int startIndex = 0)
  36. {
  37.     for (int i = startIndex; i < (str.Length - find.Length) + 1; i++)
  38.     {
  39.         bool isfound = true;
  40.         for (int j = 0; j < find.Length; j++)
  41.         {
  42.             if (str[i + j] != find[j])
  43.             {
  44.                 isfound = false;
  45.                 break;
  46.             }
  47.         }
  48.         if (isfound)
  49.             return i;
  50.     }
  51.     return -1;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment