Pregunta

quiero encontrar una manera eficiente de hacer:

tengo una cadena como:

'1,2,5,11,33'

i desee almohadilla de cero sólo para los números que por debajo de 10 (tiene un dígito)

así que quiero conseguir

'01,02,05,11,33'

gracias

¿Fue útil?

Solución

¿Cómo hacer la cantidad que realmente cuidado acerca de la eficiencia? En lo personal me gustaría usar:

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

(Como se señaló en los comentarios, si usted está utilizando .NET 3.5 que necesita una llamada a ToArray después de la Select.)

Esto definitivamente no es el más eficiente solución, pero es lo que yo usaría hasta que me había demostrado que no era lo suficientemente eficiente. Aquí hay una alternativa ...

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

Es horribles código, pero creo que va a hacer lo que quiera ...

Otros consejos

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(), ',');
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top