如果需要这样,我已经为前缀为0的整数构建了一个字符串:
// myInt as input, for example: 101;
List<string> sList = new List<string>();
string format = "00#"; // how to build format dynamicall?
for(int i= 1; i <= myInt; i++)
{
sList.Add(i.ToString(format));
}
Run Code Online (Sandbox Code Playgroud)
预期结果应该是:
001
002
...
010
...
101
Run Code Online (Sandbox Code Playgroud)
如果我的整数是10或1000,我该如何动态构建格式?
Jon*_*eet 11
怎么样 "#".PadLeft(desiredWidth, '0')
你可以得到desiredWidth从myInt.ToString().Length-有点难看,但它会工作:)
换一种说法:
List<string> sList = new List<string>();
string format = "#".PadLeft(myInt.ToString().Length, '0');
for(int i= 1; i <= myInt; i++)
{
sList.Add(i.ToString(format));
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以完全跳过格式字符串:
List<string> sList = new List<string>();
int desiredWidth = myInt.ToString().Length;
for(int i= 1; i <= myInt; i++)
{
sList.Add(i.ToString().PadLeft(desiredWidth, '0'));
}
Run Code Online (Sandbox Code Playgroud)