Created
March 12, 2020 03:35
-
-
Save imgen/67fe186389cda6cd8eda0bb7535f31a5 to your computer and use it in GitHub Desktop.
A simple named format implementation
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
public static string NamedFormat(string format, params object[] args) | |
{ | |
var newFormat = string.Empty; | |
var paraIndex = 0; | |
var paraNameIndexMap = new Dictionary<string, int>(); | |
for (int i = 0; i < format.Length; i++) | |
{ | |
var ch = format[i]; | |
if (ch == '{') | |
{ | |
var paraName = string.Empty; | |
for (i++; i < format.Length; i++) | |
{ | |
ch = format[i]; | |
if (ch == '}') | |
{ | |
break; | |
} | |
paraName += ch; | |
} | |
if (ch == '}') | |
{ | |
if (paraNameIndexMap.ContainsKey(paraName)) | |
{ | |
newFormat += "{" + paraNameIndexMap[paraName] + "}"; | |
} | |
else | |
{ | |
newFormat += "{" + paraIndex + "}"; | |
paraNameIndexMap[paraName] = paraIndex; | |
paraIndex++; | |
} | |
} | |
} | |
else | |
{ | |
newFormat += ch; | |
} | |
} | |
if (paraIndex > args.Length) | |
{ | |
throw new FormatException($"The format {format} specified more parameters than the parameters passed in"); | |
} | |
return string.Format(newFormat, args); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment