Domanda
Voglio trovare un modo efficiente di fare:
Ho una stringa come:
'1,2,5,11,33'
Voglio pad a zero solo per i numeri che sotto di 10 (ha una cifra)
in modo che io voglio ottenere
'01,02,05,11,33'
grazie
Soluzione
Quanto ti davvero cura di efficienza? Personalmente userei:
string padded = string.Join(",", original.Split(',')
.Select(x => x.PadLeft(2, '0')));
(Come sottolineato nei commenti, se si sta utilizzando .NET 3.5 avrete bisogno di una chiamata al ToArray
dopo la Select
.)
Questo non è sicuramente il più efficiente soluzione, ma è quello che vorrei utilizzare fino a quando avevo dimostrato che non era abbastanza efficiente. Ecco un'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();
}
E ' orribile di codice, ma penso che farà quello che vuoi ...
Altri suggerimenti
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(), ',');
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow