I have a certain number of files for which I need the filenames in my program. The files have a fixed naming fashion i.e. (prefix + digits).jpg. For e.g.: head001.jpg
, head002.jpg
, head003.jpg
etc. etc.
The number of digits in the end can be varying - so the program has variables to change where the file naming starts from, where it ends and how many number digits are used in the naming. For e.g: A second scenario could be - tail00001.jpg
, tail00002.jpg
, tail00003.jpg
etc. until tail00100.jpg
And in this case: start digit would be 0, end digit would be 100 and numDigits would be 5
In C++, I’ve seen this formatting being done as follows:
format <<prefix<<"%0"<<numDigits<<"d."<<filetype;
//where format
is a stringstream
However, I’m not quite sure about the best way to do this in C# and would like to know how to solve this.
Just use string.Format
, with a precision specifier saying how many digits you want:
string name = string.Format("tail{0:d6}.jpg", index);
See the MSDN documentation for standard numeric string formats for more details.
You can build the string format up programmatically of course:
string name = string.Format("tail{0:d" + digits + "}.jpg", index);
Or use PadLeft
as suggested by Vano. You might still want to use string.Format
though:
string name = string.Format("tail{0}.jpg",
index.ToString().PadLeft(digits, '0'));
Using PadLeft
has the advantage that it's easier to change the padding value, although I would imagine you'd always want it to be 0
anyway.
See more on this question at Stackoverflow