Skip to content

Instantly share code, notes, and snippets.

@ArseniySavin
Created March 29, 2018 03:31
Show Gist options
  • Save ArseniySavin/07784714989076d529db627221f3c166 to your computer and use it in GitHub Desktop.
Save ArseniySavin/07784714989076d529db627221f3c166 to your computer and use it in GitHub Desktop.
Format placeholder in string
/// <summary>
/// Format placeholder in string
/// </summary>
public static class StringExtension
{
public static string FormatPlaceholder(this string inString, params string[] param)
{
int placeholderCounter = 0;
string[] placeholder = new string[param.Length];
char[] inStringCharArray = inString.ToCharArray();
for (int i = 0; i < inStringCharArray.Length; i++)
{
try
{
// check next symbol and enlarge increment count
while (inStringCharArray[i] == '{')
if (inStringCharArray[i + 1] == '{')
i++;
else
break;
if (inStringCharArray[i] == '{')
{
int startIndex = i;
int counter = 0;
// init placeholder array use static length
char[] placeholderCharArray = new char[20];
while (inStringCharArray[startIndex] != '}')
{
placeholderCharArray[counter] = inStringCharArray[startIndex];
counter++;
startIndex++;
// add last simbol into array
if (inStringCharArray[startIndex] == '}')
placeholderCharArray[counter] = inStringCharArray[startIndex];
}
// remove empty char and create the placeholder string
placeholder[placeholderCounter] = new string(placeholderCharArray).Replace("\0", "");
placeholderCounter++;
}
}
catch (Exception e)
{
throw new ArgumentOutOfRangeException("Placeholder in string. than count params", e);
}
}
try
{
for (int i = 0; i < param.Length; i++)
{
inString = inString.Replace(placeholder[i], param[i]);
}
}
catch (Exception e)
{
throw new ArgumentOutOfRangeException("Than count params grand placeholder in string", e);
}
return inString;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment