.NET 中的字符串格式:将整数转换为固定宽度的字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6399771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 15:39:35  来源:igfitidea点击:

String format in .NET: convert integer to fixed width string?

.netstringstring-formatting

提问by pearcewg

I have an int in .NET/C# that I want to convert to a specifically formatted string.

我在 .NET/C# 中有一个 int,我想将其转换为特定格式的字符串。

If the value is 1, I want the string to be "001".

如果值为 1,我希望字符串为“001”。

10 = "010".

10 =“010”。

116 = "116".

116 = "116"。

etc...

等等...

I'm looking around at string formatting, but so far no success. I also won't have values over 999.

我正在查看字符串格式,但到目前为止还没有成功。我也不会有超过 999 的值。

采纳答案by ingo

Take a look at PadLeft.

看看PadLeft

ex:

前任:

int i = 40;

string s = i.ToString().PadLeft(3, '0'); 

s == "040"

s ==“040”

回答by vcsjones

The simplest way to do this is use .NET's built-in functionality for this:

为此,最简单的方法是使用 .NET 的内置功能:

var r = 10;
var p = r.ToString("000");

No need for looping or padding.

无需循环或填充。

回答by svick

Another option would be:

另一种选择是:

i.ToString("d3")

回答by valacar

I recall seeing code like this to pad numbers with zeros...

我记得看到这样的代码用零填充数字......

int[] nums = new int[] { 1, 10, 116 };

foreach (int i in nums)
{
    Console.WriteLine("{0:000}", i);
}

Output:

输出:

001
010
116

回答by anefeletos

If we want to use it in a function with variable fixed length output, then this approach

如果我们想在一个具有可变固定长度输出的函数中使用它,那么这种方法

public string ToString(int i, int Digits)
{
 return i.ToString(string.Format("D{0}", Digits));
}

runs 20% faster than this

运行速度比这快 20%

return i.ToString().PadLeft(Digits, '0'); 

but if we want also to use the function with a string input (e.g. HEX number) we can use this approach:

但是如果我们还想使用带有字符串输入(例如十六进制数字)的函数,我们可以使用这种方法:

public string ToString(string value, int Digits)
 {
 int InsDigits= Digits - value.Length;
 return ((InsDigits> 0) ? new String('0', InsDigits) + value : value);
 }

回答by MoarCodePlz

Every time I have needed to append things to the beginning of a string to match criteria like this I have used a while loop. Like so:

每次我需要将内容附加到字符串的开头以匹配这样的条件时,我都使用了 while 循环。像这样:

while (myString.length < 5) myString = "0" + myString;

Although there may be a string.format way to do this as well this has worked fine for me before.

虽然可能有一种 string.format 方法可以做到这一点,但以前对我来说效果很好。