Boardy
Boardy

Reputation: 36227

Formatting string to 10 characters

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

Answers (5)

soniiic
soniiic

Reputation: 2685

D8 means format as a decimal with up to 8 leading zeroes

string.Format("01{0}", counter.ToString("D8"));

Upvotes: 7

Joel Martinez
Joel Martinez

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

D Stanley
D Stanley

Reputation: 152626

try

String.Format("01{0:00000000}", i);

Upvotes: 5

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174397

You can use this:

var counter = 11;
var fixedPart = "01";
var result = fixedPart + counter.ToString().PadLeft(8,'0');

Upvotes: 3

Huusom
Huusom

Reputation: 5912

Have you tried with String.Format("00{0:00000000}", num) ?

See Custum numeric formats

Upvotes: 1

Related Questions