首页 > 解决方案 > 如何在 C# 中转换具有 C 类型占位符(%d、%x 等)的字符串

问题描述

我需要将变量插入到 C 字符串类型的占位符中。我需要用 C# 来做。(我知道在 Java 中它适用于 String.format) 请注意,我不知道有多少变量,以及期望的类型。我得到了 originalString 字符串!无法将格式更改为 C# 约定。示例:

   string originalString= "this is my number %d";
   int myNumber = 3;
   string result= string.Format(originalString, myNumber);//This doesn't work in C#!

标签: c#string

解决方案


为了匹配然后替换%d%i和类似的构造,你可以尝试正则表达式。最简单的(只是一个替代)代码可以是

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

接着

string result = MyFormat(
  "this is my number %d next number is %d and string is %s", 3, 5, "STR");

Console.Write(result); 

结果:

this is my number 3 next number is 5 and string is STR

如果您不只是要替换%d%i等等。但是实现一些详细的逻辑,你可以使用下面的代码:

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

推荐阅读