C# String formatting doesn't line up
I'm trying to build a number of strings that line up nicely, but the f开发者_JS百科ormatting 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
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.
精彩评论