Reputation: 3625
I used string format padding to display columns in specific format (i.e distance between columns).
String.Format("{0,5}{1,0}{2,-20}{3,0}",
ID,
ZIP,
State,
Flag);
It works well for standard fixed row length.
012345IL 1
112345KS 0
212345CO 1
312345CA 1
412345IL 1
512345KS 0
612345CO 1
712345CA 1
812345IL 1
912345KS 0
1012345CO 1
1112345CA 1
But the problem comes when the ID becomes double digit and the last line shifts a bit. The desired format I am expecting is
012345IL 1
112345KS 0
212345CO 1
312345CA 1
412345IL 1
512345KS 0
612345CO 1
712345CA 1
812345IL 1
912345KS 0
1012345CO 1
1112345CA 1
I tried padright and padleft, but not solved the problem and I have the same problem with the other string which has address, where the last column changes when the address length increase. Is there any other way or builtin C# function to achieve?
Upvotes: 0
Views: 4134
Reputation: 41
Your String.Format already formats your string properly. The {0,5} allows 5 characters for the first parameter. This will give you 4 spaces at the beginning of your line for single digit ids, and 3 for double digit ids. Perhaps it is an issue with how you are displaying your string.
However, what you show in your requested format is a little different.
Try this:
string firstGroup = $"{ID}{ZIP}{State}";
String.Format($"{firstGroup,-13}{Flag}");
Upvotes: 4