Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append string without hard coded value

Tags:

string

c#

.net

I have a string which looks like:

A5050MM

What I am trying to achieve is to append the end of the string so it becomes:

A5050MM01
A5050MM02
...

Currently I am doing this as follows:

string sn = "A5050MM";

for (int i = 0; i <= 99; i++)
{
   string appendVal = i < 10 ? "0" + i : i.ToString();
   string finalsn = string.Concat(sn, appendVal);
   Console.WriteLine(finalsn);
}

This works but as you can see I am hardcoding the "0" because if I don't then the output will be A5050MM1, A5050MM2 ... until 9.

My question is there another way to achieve this without hard coding the "0" or is this the only approach I will have to follow?

Thanks in advance for your help.

like image 464
Izzy Avatar asked Dec 14 '22 14:12

Izzy


1 Answers

Try using formatting (Note d2 format string - at least 2 digits):

 for (int i = 0; i <= 99; i++)
 {
     // sn followed by i which has at least 2 digits 
     string finalsn = $"{sn}{i:d2}";
     Console.WriteLine(finalsn);
 }
like image 118
Dmitry Bychenko Avatar answered Dec 24 '22 19:12

Dmitry Bychenko