C#中的格式字符串不起作用 [英] Format String in C# does not work
本文介绍了C#中的格式字符串不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Java中使用String.format方法,它运行良好。例如:
Java示例:
int min = 6;
int sec = 12;
字符串时间;
time = String.format( %2d:%2d,min,sec) ;
System.out.println(time); // 输出:06:12
但在C#中此方法不起作用。
C#示例:
int min = 6 ;
int sec = 12 ;
string 时间;
time = 字符串 .Format( % 2D:%2d中跨度>,分钟,秒);
Console.Write(time); // 输出:%2d:%2d
为什么?
如何更改以上方法才能看到与java相同的结果?
提前感谢
解决方案
不知道这是不是你的意思?否则,你将不得不解释一下......
time = String .Format( {0}:{1},min,sec);
或者如果您需要确切的格式:
time = 字符串 .Format( {0}:{1},min.ToString()。PadLeft( 2 ,' 0'),sec.ToString()。PadLeft( 2 ,' 0'));
使用格式字符串:
time = 字符串 .Format( {0:D2}:{1:D2},min,sec) ;
试试这个
但是你必须把它转换成日期时间之前这样
DateTime dt = new DateTime( 2007 , 11 , 1 ,min,sec);
然后选择时间
time = 字符串 .Format( { 0:t},dt);
hi,
I use String.format method in Java,it works well.for example:
Java Example:
int min=6;
int sec=12;
string time;
time=String.format("%2d:%2d",min,sec);
System.out.println(time); // Output: 06:12
but in C# this method does not work.
C# example:
int min=6;
int sec=12;
string time;
time=String.Format("%2d:%2d",min,sec);
Console.Write(time); //Output: %2d:%2d
why?
how can i change above method in order to see same result as java?
thanks in advance
解决方案
Don't know if this is what you mean? Otherwise, you will have to explain a little more...
time=String.Format("{0}:{1}",min,sec);
or if you need the exact format:
time=String.Format("{0}:{1}",min.ToString().PadLeft(2,'0'),sec.ToString().PadLeft(2,'0'));
[Edit: Matt Heffron]
Use format strings:
time = String.Format("{0:D2}:{1:D2}", min, sec);
try this
but you have to convert it to a datetime before like this
DateTime dt = new DateTime(2007, 11, 1,min,sec);
and then just pick the time
time=String.Format("{0:t}", dt);
这篇关于C#中的格式字符串不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文