c# fixed length string

VAAA picture VAAA · Oct 10, 2013 · Viewed 42.5k times · Source

I need to generate a text line with a fixed lenght:

What I have right now is:

StringBuilder _sb = new StringBuilder();

_sb.Append(string.Format("{0,5}", "MM")); // serie to cancel
_sb.Append(string.Format("{0,20}", "45444")); // folio to cancel
_sb.Append(string.Format("{0,30}", "AC1122")); // account number (optional)

This works great because generates a fixed lenght string of 55 characters.

The issue comes when for example the optional value is a empty string like:

StringBuilder _sb = new StringBuilder();

_sb.Append(string.Format("{0,5}", "MM")); // serie to cancel
_sb.Append(string.Format("{0,20}", "45444")); // folio to cancel
_sb.Append(string.Format("{0,30}", "")); // account number (optional)

Having empty string inside the string.format then wont give a fixed length, and I still need to have a 30 chars length.

Any clue is well appreciated!!

Thanks

Answer

Szymon picture Szymon · Oct 10, 2013

You can use PadLeft method:

StringBuilder _sb = new StringBuilder();

_sb.Append("MM".PadLeft(5)); // serie to cancel
_sb.Append("45444".PadLeft(20)); // folio to cancel
_sb.Append("".PadLeft(30)); // account number (optional)