Created
August 5, 2021 13:34
-
-
Save wcoder/de8bf313420c5921094c7e40050c6502 to your computer and use it in GitHub Desktop.
The example demonstrates the use of square brackets to extend the C # string.Format ()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
public static class StringExtensions | |
{ | |
public static string Format(this string str, params object[] parameters) | |
{ | |
return string.Format(str, parameters); | |
} | |
public static string FormatExt(this string str, params object[] parameters) | |
{ | |
var result = System.Text.RegularExpressions.Regex.Replace( | |
str, | |
@"\[(\d+)\]", | |
m => parameters[int.Parse(m.Groups[1].Value)].ToString()); | |
return result; | |
} | |
} | |
// Example: | |
class Program | |
{ | |
static void Main() | |
{ | |
var result = "my [1] name: {0}, my profile [0] link" | |
.Format("Qwerty") | |
.FormatExt("test", "new value"); | |
Console.WriteLine(result); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Demo