C # pad left to string

I want to find an effective way:

I have a line like:

'1,2,5,11,33' 

I want to impose a zero only on numbers that are below 10 (have one digit)

so i want to get

 '01,02,05,11,33' 

thank

+4
string c # pad
Dec 13 '10 at 19:33
source share
2 answers

How much do you really care about efficiency? Personally, I would use:

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

(As pointed out in the comments, if you are using .NET 3.5, you will need to call ToArray after Select .)

This is definitely not the most effective solution, but it is what I will use until I prove that it is not effective enough. Here is 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(); } 

This is terrible code, but I think it will do what you want ...

+17
Dec 13 '10 at 19:36
source share
 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(), ','); 
+4
Dec 13 '10 at 19:36
source share



All Articles