有没有办法转换成C-格式字符串在C#C#-format串/。NET 2.0吗? [英] Is there a way to convert C-format strings for C# -format strings in C#/.NET 2.0?

查看:109
本文介绍了有没有办法转换成C-格式字符串在C#C#-format串/。NET 2.0吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我想字符串转换是这样的:

So i would like to convert string like this:

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

用C#相当于.Format或.AppendFormat方法

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

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

抱歉,但我不知道如果C#版本是正确的,但你长了这个想法。该解决方案并不一定是完美的,但覆盖的基本情况。

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.

感谢和放大器; BR -Matti

Thanks & BR -Matti

回答我的其他问题的 http://stackoverflow.com/questions/4098533/how-to-write-c-regular-expression-pattern-to-match-basic -printf格式串-L

推荐答案

第一次尝试:这个(有点)忽视了之间的一切 diouxXeEfFgGaAcpsn 之一,并替换了 [KP} 其中, K 从0到最大的99(代码不检查:超过100 输入退货一个坏的格式字符串)。

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

这篇关于有没有办法转换成C-格式字符串在C#C#-format串/。NET 2.0吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆