• # Leading zero in string

i.e. string contain hyphen(-).

Example:

input.
1-1-12,
10-2-1,
1-2-3

Output

01-01-12,
10-02-01,
01-02-03
• What is your requirement? Can you explain the issue little bit clearly. So that we can try to solve it.
By Nathan
Direction is important than speed

• i want convert the the string like..

1-1-12 -->01-01-12,
1-1--->01-01,
1-->01

• Can you please explain you requirement little much better ?

• Hi,
Try this:
` string szInput = "1-1-12"; string szOutput = ""; foreach (string szValue in szInput.Split('-')) { if (szValue.Length < 2) szOutput = szOutput.Trim() == "" ? (szValue.PadLeft(szValue.Length + 1, '0').Trim() + "-") : (szOutput.Trim() + szValue.PadLeft(szValue.Length + 1, '0').Trim() + "-"); else szOutput = szOutput.Trim() == "" ? (szValue + "-") : (szOutput + szValue + "-"); } if (szOutput.EndsWith("-")) szOutput = szOutput.Remove(szOutput.LastIndexOf("-")); Console.WriteLine(szOutput);`

• If you want to achieve it in sql server. you can use code like below

declare @b as varchar(255)
set @b = ''
declare @a as varchar(100)
set @a = '-1-11-1-2-';--assign your value here
with tbl_for_csv as
(
select left(@a, charindex('-',@a) - 1) as val,
stuff(@a +'-',1,charindex('-',@a),'') as col
union all
select cast(left(col, charindex('-',col) - 1) as varchar(100)),
stuff(col,1,charindex('-',col),'') from tbl_for_csv
where col <> ''
)

select @b = @b + case when len(val) < 2 then replicate('0',2-len(val))+ Val else val end + '-' from tbl_for_csv

select left(@b,len(@b)-1)

Many Thanks
Tejinder Singh Barnala
/*I have the simplest tastes. I am always satisfied with the best*/