Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

How to convert a string with C type placeholders (%d, %x etc.) in C#


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();
  });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...