Question

Je veux trouver un moyen de faire efficent:

J'ai une chaîne comme:

'1,2,5,11,33'

je veux pad zéro uniquement aux chiffres qui en dessous de 10 (ont un chiffre)

donc je veux

'01,02,05,11,33'

Merci

Était-ce utile?

La solution

Combien avez-vous vraiment se soucier de l'efficacité? Personnellement, j'utiliser:

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

(Comme indiqué dans les commentaires, si vous utilisez .NET 3.5, vous aurez besoin d'un appel à ToArray après la Select.)

C'est certainement pas le la plus efficace solution, mais il est ce que j'utiliser jusqu'à ce que je l'avais prouvé qu'il était pas assez efficace. Voici une 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();
}

Il est horribles code, mais je pense que ça va faire ce que vous voulez ...

Autres conseils

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(), ',');
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top