我有一个静态字符串:C#增量数字字符串
static string SERIAL =“000”;
我需要在特定条件下将其增加1。例如,值应该是这样的:
001
002
003
等等。
我已经尝试了不同的方法,但一直没能弄明白
我有一个静态字符串:C#增量数字字符串
static string SERIAL =“000”;
我需要在特定条件下将其增加1。例如,值应该是这样的:
001
002
003
等等。
我已经尝试了不同的方法,但一直没能弄明白
你可以有串行值作为一个整数,定义了getter这将返回该值所需格式的字符串。这样你可以简单地递增序列的数字值。
举个例子:
public class Program
{
static void Main(string[] args)
{
Console.WriteLine(Counter.SerialString);
Counter.Serial++;
Console.WriteLine(Counter.SerialString);
Console.ReadKey();
}
public class Counter
{
public static int Serial;
public static string SerialString
{
get
{
return Serial.ToString("000");
}
}
}
}
如果串行总是3位长,您可以使用一个整数,当你需要它作为一个字符串,只需调用其ToString()
方法。
一种方法是在ToString方法上使用PadLeft方法。
int n = 000;
for (int i = 0; i < 100; i++)
{
n++;
Console.WriteLine(n.ToString().PadLeft(3, '0'));
}
Console.ReadLine();
赫雷什方法头 公共字符串PadLeft(INT totalWidth,炭paddingChar);
你尝试了什么? –
你为什么使用字符串? – ChrisBint
事实上,使用'int',增加它,然后只需调用'mySerialInt.ToString(“000”)' –