有没有办法在 C#/.NET 2.0 中将 C 格式字符串转换为 C# 格式字符串?

发布于 2024-09-30 18:36:26 字数 526 浏览 1 评论 0原文

所以我想像这样转换字符串:

"Bloke %s drank %5.2f litres of booze and ate %d bananas"

使用 .Format 或 .AppendFormat 方法的 C# 等效项,

"Bloke {0} drank {1,5:f2} litres of booze and ate {2} bananas"

抱歉,但我不确定 C# 版本是否正确,但你明白了。解决方案不必是完美的,但可以涵盖基本情况。

谢谢& BR -Matti

在我的另一个问题中回答了 如何编写 C# 正则表达式模式来匹配基本 printf 格式字符串,如“%5.2f”?

So i would like to convert string like this:

"Bloke %s drank %5.2f litres of booze and ate %d bananas"

with a C# equivalent for .Format or .AppendFormat methods

"Bloke {0} drank {1,5:f2} litres of booze and ate {2} bananas"

sorry but i'm not sure if the C# version was correct but u got the idea. The solution does not have to be perfect but cover the basic case.

Thanks & BR -Matti

answered in my other question How to write C# regular expression pattern to match basic printf format-strings like "%5.2f"?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

我做我的改变 2024-10-07 18:36:26

您可能只使用StringBuilder.Replace()

StringBuilder cString = new StringBuilder("Bloke %s drank %5.2f litres of booze and ate %d bananas");
cString.Replace("%s","{0}");
cString.Replace("%5.2f", "1,5:f2"); // I am unsure of this format specifier
cString.Replace("%d", "{2}");

string newString = String.Format(cString.ToString(), var1, var2, var3);

可以想象,您可以添加类似的内容作为 String 的扩展方法,但我认为您最大的问题将是特殊格式的说明符。如果这在这方面很重要,您可能需要设计一个正则表达式来捕获这些并有意义地执行替换。

You could probably just use StringBuilder.Replace().

StringBuilder cString = new StringBuilder("Bloke %s drank %5.2f litres of booze and ate %d bananas");
cString.Replace("%s","{0}");
cString.Replace("%5.2f", "1,5:f2"); // I am unsure of this format specifier
cString.Replace("%d", "{2}");

string newString = String.Format(cString.ToString(), var1, var2, var3);

Conceivably you could add something like this to as an extension method to String, but I think your biggest problem is going to be the specially formatted specifiers. If it is non-trivial in this aspect, you may need to devise a regular expression to catch those and perform the replace meaningfully.

微暖i 2024-10-07 18:36:26

第一次尝试:这(有点)忽略 %diouxXeEfFgGaAcpsn 之间的所有内容,并将其替换为 {k} 其中 k 从 0 到最大 99(未在代码中检查:输入中超过 100 % 返回错误的格式字符串)。

这并不认为指令中的 * 是特殊的。

#include <string.h>

void convertCtoCSharpFormat(char *dst, const char *src) {
  int k1 = 0, k2 = 0;
  while (*src) {
    while (*src && (*src != '%')) *dst++ = *src++;
    if (*src == '%') {
      const char *percent;
      src++;
      if (*src == '%') { *dst++ = '%'; continue; }
      if (*src == 0) { /* error: unmatched % */; *dst = 0; return; }
      percent = src;
      /* ignore everything between the % and the conversion specifier */
      while (!strchr("diouxXeEfFgGaAcpsn", *src)) src++;

      /* replace with {k} */
      *dst++ = '{';
      if (k2) *dst++ = k2 + '0';
      *dst++ = k1++ + '0';
      if (k1 == 10) { k2++; k1 = 0; }
      /* *src has the conversion specifier if needed */
      /* percent points to the initial character of the conversion directive */
      if (*src == 'f') {
        *dst++ = ',';
        while (*percent != 'f') *dst++ = *percent++;
      }
      *dst++ = '}';
      src++;
    }
  }
  *dst = 0;
}

#ifdef TEST
#include <stdio.h>
int main(void) {
  char test[] = "Bloke %s drank %5.2f litres of booze and ate %d bananas";
  char out[1000];

  convertCtoCSharpFormat(out, test);
  printf("C fprintf string: %s\nC# format string: %s\n", test, out);
  return 0;
}
#endif

First attempt: this (kinda) ignores everything between a % and one of diouxXeEfFgGaAcpsn and replaces that with a {k} where k goes from 0 to a maximum of 99 (not checked in code: more than 100 % in the input returns a bad format string).

This does not consider the * in a directive special.

#include <string.h>

void convertCtoCSharpFormat(char *dst, const char *src) {
  int k1 = 0, k2 = 0;
  while (*src) {
    while (*src && (*src != '%')) *dst++ = *src++;
    if (*src == '%') {
      const char *percent;
      src++;
      if (*src == '%') { *dst++ = '%'; continue; }
      if (*src == 0) { /* error: unmatched % */; *dst = 0; return; }
      percent = src;
      /* ignore everything between the % and the conversion specifier */
      while (!strchr("diouxXeEfFgGaAcpsn", *src)) src++;

      /* replace with {k} */
      *dst++ = '{';
      if (k2) *dst++ = k2 + '0';
      *dst++ = k1++ + '0';
      if (k1 == 10) { k2++; k1 = 0; }
      /* *src has the conversion specifier if needed */
      /* percent points to the initial character of the conversion directive */
      if (*src == 'f') {
        *dst++ = ',';
        while (*percent != 'f') *dst++ = *percent++;
      }
      *dst++ = '}';
      src++;
    }
  }
  *dst = 0;
}

#ifdef TEST
#include <stdio.h>
int main(void) {
  char test[] = "Bloke %s drank %5.2f litres of booze and ate %d bananas";
  char out[1000];

  convertCtoCSharpFormat(out, test);
  printf("C fprintf string: %s\nC# format string: %s\n", test, out);
  return 0;
}
#endif
×纯※雪 2024-10-07 18:36:26
Regex pattern = new Regex(@"%[+\-0-9]*\.*([0-9]*)([xXeEfFdDgG])");
//prepare for regex
string csharpformat = originaltext.Replace("%%", "%").Replace("{", "{{").Replace("}", "}}").Replace("%s", "{0}");
                
newFormat = pattern.Replace(csharpformat, m =>
{
    if (m.Groups.Count == 3)
    {
        return "{0:" + m.Groups[2].Value + m.Groups[1].Value + "}";
    }
    return "{0}";
});

它捕获 %.2f 并转换为 {0:f2}

Regex pattern = new Regex(@"%[+\-0-9]*\.*([0-9]*)([xXeEfFdDgG])");
//prepare for regex
string csharpformat = originaltext.Replace("%%", "%").Replace("{", "{{").Replace("}", "}}").Replace("%s", "{0}");
                
newFormat = pattern.Replace(csharpformat, m =>
{
    if (m.Groups.Count == 3)
    {
        return "{0:" + m.Groups[2].Value + m.Groups[1].Value + "}";
    }
    return "{0}";
});

It catches %.2f and converts to {0:f2}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文