4

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.

2

5 Answers 5

6

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);
 }
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your help
4

You can use the overload of ToString that takes a format:

string sn = "A5050MM";

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

See a live demo on rextester.

4 Comments

Hi, I get the following error with this Argument 1: cannot convert from 'string' to 'System.IFormatProvider'
Works fine for me... I've added a live demo link.
I think it was causing an error because before the edit you had appendVali.ToString("00")); and now I did i.ToString("00") and it works as expected. Thanks for your help I will accept this as you was the first to answer
Yeah, that was a typo... Glad to help :-)
0

you can use also the D2 in toString liek

        string sn = "A5050MM";

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

Comments

0

You can use PadLeft function

    string sn = "A5050MM";
    for (int i = 0; i <= 99; i++)
    {
        string finalsn = sn + i.ToString().PadLeft(2, '0');
        Console.WriteLine(finalsn);
    }

Comments

0
Enumerable.Range(0, 99)
    .Select(x => String.Format("A5050MM{0:d2}", x))
    .ToList()
    .ForEach(x => Console.WriteLine(x));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.