I am trying to align values. I wonder why this happen :
string value = "";
value += string.Format("{0,-10}", "value");
value += string.Format("{0,5}", "value");
value += Environment.NewLine;
value += string.Format("{0,-8}", "val");
value += string.Format("{0,7}", "value");
Print(value);
If i check value before i "Print" it is correct. The result is:
value value
val value
As they should be, but when i print "value" to my printer then they get like this :
value value
val value
I really cant understand why it changes the string when i print the text?
I have tried to use "\t" but my printer dont seem to understand "\t" because the tabs isnt printed out.
Btw: this is just a test code so you could understand the problem that i am having with the real code.
your console uses fixed width fonts where your printer does not (at least by default). So spaces take up less space on your printer and your letters take up more or less space based on their actual width.
This could be caused by a font that uses different character widths. In non-fixed-width fonts, spaces are often narrower than letters and numbers, so it might seem that spaces are missing. Consider using Lucida Console or another fixed-width font.
Related
I managed to make a simple C# table in a console, there are more than enough threads regarding that.
The problem is due to characters having different sizes(for example 'iiiii'(5 chars) is shorter than 'there'(5 chars)) The table will never be aligned.
Is there a way to calculate the real length of the string value in order to tell how many more spaces need to be added to align the shorter string with the rest of the table?
(I tried to visually display it here but it seems that in the font this site is using all characters have an equal size(and/or padding), However, I can send a screenshot)
Instead of trying to manually align the text into columns with arbitrary strings of spaces, you should embed actual tabs (the \t escape sequence) into each output string.
Console.WriteLine("Row1:" + "\t"
+ "iiiiiii" );
Console.WriteLine("Row2:" + "\t"
+ "7 chars" );
If you know console font name and size, you can try to use TextRenderer.MeasureText to get strings widths in pixels. Then add spaces to shorter ones until strings will be aligned.
Of course you will not get precise positioning this way, but probably it will suit your needs.
UPD. You can refer to How to measure the pixel width of a digit in a given font / size (C#) and/or other similar questions for more details.
I have a WinForms application, in which I have a label, where I bind a decimal to. I have also added a .Format method to the binding. Like this:
// Add data binding for the lavel
Binding bindWithFormat = new Binding("Text", viewModel, nameof(viewModel.BindingNumber));
bindWithFormat .Format += viewModel.FormatAsNumber;
lblNumber.DataBindings.Add(bindWithFormat);
// Formatting function
public void FormatAsNumber(object sender, ConvertEventArgs e)
{
// The method converts only to string type. Test this using the DesiredType.
if (e.DesiredType != typeof(string)) return;
// Formats the value with thousand separator and zero decimals
e.Value = String.Format("{0:N0}", e.Value);
}
This works fine under normal circumstances, but if I choose a particular type of Digit Grouping Symbol, it looks like this (it is supposed to show "15 000 000"):
I first thought it was when I used a blank space (" ") as symbol, but when I explicitly type a blank space, then it shows it as intended. However, there is another symbol I can chose in the regional settings, which looks like a space, but it causes the above formatting error when selected (unlike when I explicitly type space):
What the heck is going on? According to this website, the symbol is "no break space" (U+00A0). So it is a space. But not a space. And for some reason, it seriously messes up the formatting. What to do?
Bonus info: After playing around some more, it seems to only affect that specific font, that I was using (it only exists in my company). If I change fonts to e.g. Segoe UI, then the problem disappears.
Is there a way to perfectly align two strings in C#?
I am trying to align the string "CBI" with "Central Bureau of Investigation" and I want both strings to occupy 35 characters. I use the function
string.Format("{0,-35}", str);
to format both strings. But they do not appear to be aligned properly. Does it have something to do with the font settings?
I have to use these strings in a chart in excel and they have to occupy the same width on the screen
Yes there is PadLeft and PadRight
str.PadLeft(35);
str.PadRight(35);
str = "BBQ and Slaw";
Console.WriteLine(str.PadLeft(15)); // Displays " BBQ and Slaw".
Console.Write(str.PadRight(15)); // Displays "BBQ and Slaw ".
Side Note from documentation:
However, if totalWidth is less than the length of this instance, the method returns a reference to the existing instance
Basically if your length is less than the length of the string then an reference of the existing string is returned
If EvenMcDonnal wishes to include this in an answer I'll gladly remove it from my answer.
You can find a list of MonoSpaced fonts you can use here
I find that I am never satisfied by monospaced fonts, so I use character padding with a micro-space character (about 1 pixel wide) (char)0x200A to line things up. This is especially useful when simulating column alignment with a list of strings. The most flexible method is to use a while loop comparing string pixel widths and adding the space character until the match. I use System.Windows.Forms.TextRenderer.MeasureText() with a NoPadding flag and just to be save, an initial size of int.MaxValue, then check the Width parameter of System.Drawing.Size. If you feed in any Font in the MeasureText constructor, it works with any font.
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
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.
I am trying to align values.
I wonder why this happen :
string value = "";
value += string.Format("{0,-10}", "value");
value += string.Format("{0,5}", "value");
value += Environment.NewLine;
value += string.Format("{0,-8}", "val");
value += string.Format("{0,7}", "value");
MessageBox.Show(value);
If i check value before i do "MessageBox.Show() it is correct. The result is:
value value
val value
As they should be, but when i do MessageBox.show() then they get like this :
value value
val value
I really cant understand why it changes the string with show()? Same thing happens when i am trying to print "value", then it doesnt align correct.
Btw: this is just a test code so you could understand the problem that i am having with the real code.
This might be caused by the fact that the font used in the message box is not monospaced, meaning that each character takes an equal amount of horizontal space. The font you are using in the Visual Studio debugger probably is, which is why the padding looks entirely different.
You could try if using tabs instead of spaces for your formatting gives better results.
That's because the font used by MessageBox.Show doesn't have a fixed width...
According to this answer the way to go is using \t as a column seperator.
This definitely involves checking the length of all the words of each single column. This way you would know whether to use a single \t or double \t\t etc.