Reputation: 36227
I am currently working on a project where I need to format a string to be only 10 characters long. But has to start in a certain way and finish with an incrementing counter.
E.G the number will be in the format of:
0100000001
0100000002
0100000003
...
0100000010
0100000011
I.e. the first two numbers will stay the same only the last digits will keep incrementing but the string has to remain 10 characters long.
How could I do this I have tried using String.Format but doesn't appear to work.
UPDATE I've tried using the following
destination = String.Format("07000000{0}", messageCount);
This kind of works but once the messageCount gets above 10 the length becomes 11 and it needs to stay no longer than 10
Upvotes: 7
Views: 14047
Reputation: 2685
D8
means format as a decimal with up to 8 leading zeroes
string.Format("01{0}", counter.ToString("D8"));
Upvotes: 7
Reputation: 47799
Give this extension method a shot ... I didn't compile it, but let me know if it works :-)
public static class Ex
{
public static string ToSpecialString(this string value)
{
int desiredLength = 10;
string prefix = "01";
string padding = new String('0', desiredLength - prefix.Length - value.Length);
return prefix + padding + value;
}
}
... usage ...
Console.WriteLine( "32".ToSpecialString() );
// should output "0100000032"
Upvotes: 0
Reputation: 174397
You can use this:
var counter = 11;
var fixedPart = "01";
var result = fixedPart + counter.ToString().PadLeft(8,'0');
Upvotes: 3