[英]c# pad left to string
我想找到一個有效的方法:
我有一個像這樣的字符串:
'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,那么在Select
之后您需要調用ToArray
。)
這絕對不是最有效的解決方案,但在我證明它不夠有效之前,我會使用它。 這是另一種選擇......
// 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(), ',');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.