Click here to Skip to main content
15,884,298 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am making a program that take user input and increment it.
Assume input is 001 it will be 002, 003 etc.
assume input is 01 it will be 02, 03 etc
assume input is 1 it will be 2, 3 etc so on.
I know we have to convert input to string save the padding of zeros increment the int and put the 2 variables together but I don't know how to implement it.
This is what I have.

What I have tried:

int Number = number;
    foreach (FileInfo file in files)
            {
 graphics.DrawString((preFix + (Number++).ToString().PadLeft(batesNumber, '0')), font, brush, position);
}

I think I need to do the padding outside of the foreach and replace the '0' with a variable string that has number of zeros based on user input. then increment the int inside the forech and just append the string of zeros to that int. Thanks
Posted
Updated 8-Jan-20 8:52am
Comments
Richard MacCutchan 8-Jan-20 15:16pm    
You just need to scan the input as a string and count the number of digits. You can then use that value to set the padding on output.

1 solution

I would do it like this:
C#
string input = "000001";
int padding = input.Length;
string template = string.Format("{{0:d0{0}}}", padding); // {0:d04}

for (int number = 1; number < 15; number++)
{
    var paddedNumber = string.Format(template, number);
    Console.WriteLine(paddedNumber);
}
 
Share this answer
 
v2
Comments
AskalotLearnalot 8-Jan-20 15:04pm    
Thank you for the replay,I think this neglects the user input. from my understanding padding will be always 4 or less what if user input 000001
Tomas Takac 8-Jan-20 15:38pm    
I updated the solution, what about now?
AskalotLearnalot 8-Jan-20 15:43pm    
if user input 01 the out put will be 000001 it should be 01, etc.
Tomas Takac 8-Jan-20 15:54pm    
I don't follow. The input variable in the sample represents your input. Try to run it with input = "01" and you will see it works.
AskalotLearnalot 8-Jan-20 16:26pm    
You are very correct I am sorry I responded too fast. Thanks for the clarification here is what i did:
string Number = number;
int padding = Number.Length;
string template = string.Format("{{0:d0{0}}}", padding);
foreach{
//(padding++)) will make number start at user input then ++ 
 var paddedNumber = string.Format(template, (padding++)); 
  graphics.DrawString((preFix + (paddedNumber)), font, brush, position);
}

hopefully one day I will have enough knowledge to help others like you do

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900