2010-11-04 86 views
1

所以我想字符串轉換是這樣的:有沒有辦法在C#/。NET 2.0中爲C#格式字符串轉換C格式字符串?

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

用C#等效.Format或.AppendFormat方法

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

抱歉,但我不知道如果C#版本是正確的但你明白了。該解決方案不一定非常完美,但涵蓋了基本情況。

感謝& BR -Matti

回答我的其他問題How to write C# regular expression pattern to match basic printf format-strings like "%5.2f"?

+0

基於字符串搜索和替換的解決方案如何? – 2010-11-04 14:08:28

+0

任何相當快的東西!大多數字符串沒有這些C佔位符,所以當有0個C佔位符時它應該很快。這絕對不是微不足道的,我想知道解決方案是否已經存在,因爲這可能是常見問題。 – 2010-11-04 14:13:11

+0

OP與此類似的問題:[如何編寫C#正則表達式模式來匹配基本的printf格式字符串,例如「%5.2f」?](http://stackoverflow.com/questions/4098533/) – 2010-11-04 16:26:52

回答

0

你很可能只是用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); 

可以想象,你可以添加這樣的事情作爲一個擴展方法的字符串,但我覺得你最大的問題將是在特殊格式符。如果在這方面不重要,則可能需要設計一個正則表達式來捕獲這些表達式並進行有意義的替換。

+0

如果這是這麼簡單,我不會問:http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/ – 2010-11-04 14:28:11

+0

這是一個例子。因此「convert string _like_ this」。 – 2010-11-04 14:31:25

+4

-1:這是針對無法硬編碼的問題的硬編碼解決方案。一個工作解決方案將比這更復雜。 – Brian 2010-11-04 14:32:21

0

首先嚐試:此(有點)忽略一個%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 
+0

感謝您的努力。正如它在標題中所說的,我正在尋找C#2.0解決方案。我自然明白C,所以我檢查將它轉換爲C#是否合理。不管怎麼說,還是要謝謝你。 – 2010-11-04 15:26:16

+0

啊,大聲笑 - 我沒有讀到標題:) – pmg 2010-11-04 15:32:31