Streamwriter格式化

0 .net c# string-formatting

我必须以特殊格式打印出count变量(非负数):

  1. 结果字符串的总长度应该是20个字符;
  2. 如有必要,应将'0'字符添加到字符串的左侧.

例如:

  2   -> "00000000000000000002" // <- The length of each string is 20
  30  -> "00000000000000000030"
  123 -> "00000000000000000123"
Run Code Online (Sandbox Code Playgroud)

在.Net中实现这一目标的最佳方法是什么?

Dmi*_*nko 6

你可以使用PadLeft:

String value = "2";
String result = value.PadLeft(20, '0'); // <- 20 is desired string length, '0' - padding
Run Code Online (Sandbox Code Playgroud)

另一种可能性(如果你有整数值)是格式化:

int value = 2;
String result = value.ToString("D20");
Run Code Online (Sandbox Code Playgroud)