c#pad left to string

时间:2010-12-13 19:33:41

标签: c# string pad

我想找到一种有效的方法:

我有一个字符串:

'1,2,5,11,33'

我想仅将零填充到低于10(有一位数)的数字

所以我想得到

'01,02,05,11,33'

感谢

2 个答案:

答案 0 :(得分:18)

真正关心效率多少?就我个人而言:

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();
}

这是可怕的代码,但我认为它会做你想要的......

答案 1 :(得分:5)

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(), ',');