题
我想找到一种有效的方法:
我有一个类似:
'1,2,5,11,33'
我只想将零以低于10的数字添加(拥有一个数字)
所以我想得到
'01,02,05,11,33'
谢谢
解决方案
你多少钱 真的 关心效率?我个人会使用:
string padded = string.Join(",", original.Split(',')
.Select(x => x.PadLeft(2, '0')));
(如评论中指出的那样,如果您使用.NET 3.5,则需要打电话给 ToArray
之后 Select
.)
那绝对不是 最有效 解决方案,但这是我要使用的方法,直到我证明它不够有效。这是一个替代...
// Make more general if you want, with parameters for the separator, length etc
public static string PadCommaSeparated(string text)
{
StringBuilder builder = new StringBuilder();
int start = 0;
int nextComma = text.IndexOf(',');
while (nextComma >= 0)
{
int itemLength = nextComma - start;
switch (itemLength)
{
case 0:
builder.Append("00,");
break;
case 1:
builder.Append("0");
goto default;
default:
builder.Append(text, start, itemLength);
builder.Append(",");
break;
}
start = nextComma + 1;
nextComma = text.IndexOf(',', start);
}
// Now deal with the end...
int finalItemLength = text.Length - start;
switch (finalItemLength)
{
case 0:
builder.Append("00");
break;
case 1:
builder.Append("0");
goto default;
default:
builder.Append(text, start, finalItemLength);
break;
}
return builder.ToString();
}
它是 可怕 代码,但我认为它会做您想要的...
其他提示
string input= "1,2,3,11,33";
string[] split = string.Split(input);
List<string> outputList = new List<string>();
foreach(var s in split)
{
outputList.Add(s.PadLeft(2, '0'));
}
string output = string.Join(outputList.ToArray(), ',');
不隶属于 StackOverflow