In order to match and then replace %d
, %i
and the like consructions, you can try regular expressions. The simplest (just a substitution) code can be
using System.Text.RegularExpressions;
...
private static string MyFormat(string source, params object[] args) {
int index = 0;
return Regex.Replace(source, "%[isdf]", match => args[index++]?.ToString());
}
And then
string result = MyFormat(
"this is my number %d next number is %d and string is %s", 3, 5, "STR");
Console.Write(result);
Outcome:
this is my number 3 next number is 5 and string is STR
If you want not just to replace %d
, %i
ect. but implement some elaborated logic you can use the code below:
private static string MyFormat(string source, params object[] args) {
int index = 0;
return Regex.Replace(source, "%[sdfx]", match => {
string pattern = match.Value.TrimStart('%'); // "s", "d", "x" and the like
object value = args[index++]; // 3, 5, STR etc
//TODO: apply special logic here and return the formatted value
return value.ToString();
});
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…