c# pad left to string

落花浮王杯 提交于 2020-01-03 09:13:25

问题


i want to find a efficent way to do :

i have a string like :

'1,2,5,11,33'

i want to pad zero only to the numbers that below 10 (have one digit)

so i want to get

'01,02,05,11,33'

thanks


回答1:


How much do you really care about efficiency? Personally I'd use:

string padded = string.Join(",", original.Split(',')
                                         .Select(x => x.PadLeft(2, '0')));

(As pointed out in the comments, if you're using .NET 3.5 you'll need a call to ToArray after the Select.)

That's definitely not the most efficient solution, but it's what I would use until I'd proved that it wasn't efficient enough. Here's an alternative...

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

It's horrible code, but I think it will do what you want...




回答2:


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


来源:https://stackoverflow.com/questions/4432734/c-sharp-pad-left-to-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!