有没有办法在 C#/.NET 2.0 中将 C 格式字符串转换为 C# 格式字符串?
所以我想像这样转换字符串:
"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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可能只使用
StringBuilder.Replace()
。可以想象,您可以添加类似的内容作为 String 的扩展方法,但我认为您最大的问题将是特殊格式的说明符。如果这在这方面很重要,您可能需要设计一个正则表达式来捕获这些并有意义地执行替换。
You could probably just use
StringBuilder.Replace()
.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.
第一次尝试:这(有点)忽略
%
和diouxXeEfFgGaAcpsn
之间的所有内容,并将其替换为{k}
其中k
从 0 到最大 99(未在代码中检查:输入中超过 100%
返回错误的格式字符串)。这并不认为指令中的
*
是特殊的。First attempt: this (kinda) ignores everything between a
%
and one ofdiouxXeEfFgGaAcpsn
and replaces that with a{k}
wherek
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.它捕获
%.2f
并转换为{0:f2}
It catches
%.2f
and converts to{0:f2}