0

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?

4
  • A better idea could be the string count and use spaces instead of padding. So if the ID size is increased your location of next column will still be same. Commented Mar 6, 2017 at 3:38
  • @MohitShrivastava Can you please answer with the prototype of your concept ? Commented Mar 6, 2017 at 3:46
  • how do you show your result? Because I am seeing padded strings (spaces) in front of each result, which makes them what you wanted already Commented Mar 6, 2017 at 4:21
  • padding 0 doesn't affect the output of my format Commented Mar 6, 2017 at 4:23

1 Answer 1

4

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}");
Sign up to request clarification or add additional context in comments.

2 Comments

Is this syntax belongs to c# ?
@berdem: Yes, it is called an "interpolated string". It has been supported since c# 6, July 2015.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.