Some String Formatting Examples with C#

First, check out this good blog post:

So, my example was that a flat file I’m parsing contains the social security number, but with no “-” dashes. 

ie. 111223333

(note this is a string in the flat file).


string ssn = String.Format("{0:###-##-####}", Int32.Parse(swipe.MemberID));

The format is expecting a number, so I convert the “111223333” into number, then feed it into the String.Format.  Works like a charm…


EDIT: Bug fix alert! Although the above does work – it does not take into account of leading zero’s!  The fix is:

string ssn = String.Format("{0:000-00-0000}", Int32.Parse(swipe.MemberID));
This will preserve any leading zeros


Here is another fun one, I have a date in CCYYMMDD  (yyyyMMdd)

DateTime serviceDate = DateTime.ParseExact(swipe.TransactionDate,
 "yyyyMMdd", new CultureInfo("en-US"));

Last little gem:

taking a int of 0 or 1 and making it ‘yes’ or ‘no’ :

String.Format(”{0:yes;;no}”, value)

=> yes if value == 1
=> no if value == 0

That is handy  🙂


John Sheehan has a nice ‘cheat sheet’ section of his website: .NET Format String Quick Reference


4 thoughts on “Some String Formatting Examples with C#

  1. I love the last one (yes/no). Never knew that one.

    The first one (SSN) has to be killer on performance which depending on the file size, could kill parse times. You are likely better off doing a hard parse on the string/char[] than the int conversion and string format.

    Love the new site design by the way.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s