0

I'm trying to build a number of strings that line up nicely, but the formatting isn't working the way I would expect.

If I have:

String.Format("{0,-25}{1,-7}{2,-18}{3,-8}{4,-15}{5,-3}{6,-10}",
              i.Name, "Price: ", i.Price.toString(), "Weight: ",
              i.Weight.toString() + " lbs", "Quantity:",i.Quantity.toString()));

I would expect to get Name (which is a string) starting at the beginning of the line, then "Price" starting at character 26, and so on. (None of the names are more than 10 characters). Instead, the second column is all over the place depending on the length of name.

I tried this using a StringBuilder as well, with the same result. A number of internet searches are just showing code that looks pretty much the same as what I have, so I'm not sure what's not working.

Edit: fixed typos

2
  • 6
    Are you displaying the results in a monospace font? Commented Jun 10, 2011 at 16:49
  • The code you have provided contains several errors. You are passing a "c" format to what would be a string value, if it were capitolized correctly (the tag is C#, not Java!). You have a slash at the end where a period is probably what you mean. I suspect the problem may be apparent if you were to post the real code that you are having trouble with. Commented Jun 10, 2011 at 16:55

1 Answer 1

1

I suspect that the problem is the display rather than the strings themselves. These sorts of alignments only work when the font is a monospace font. A monospace font is one in which each character is the same width. There are several of these provided with Windows,Office, Visual Studio. Many people consider "Consolas" to be the best.

I recommend you change the font of whatever control is displaying your data to Consolas.

Sign up to request clarification or add additional context in comments.

Comments

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.