What is the optional argument in C# interpolated string for? - c#

Interpolated strings is one of the new features of C# 6.0.
According to MSDN, the syntax of the embedded C# expressions can contain an optional, comma-separated value, deemed as <optional-comma-field-width> in the documentation.
Unfortunately I didn't find what this field is for.
From its name one might think that this value sets the maximal size of the "interpolated" field, but when I try the following expression:
var p = Process.GetCurrentProcess();
Console.WriteLine($"Process name is {p.ProcessName, 5}");
I get the following output:
Process name is LINQPad.UserQuery

It's the minimum width to use for that field, not the maximum. Since your string is longer than the 5 characters you specify for the width, the field is extended to the length of your string. You'll see the difference more dramatically with a longer width:
var p = Process.GetCurrentProcess();
$"Process name is {p.ProcessName, 50}".Dump();
yields:
Process name is LINQPad.UserQuery
A positive field size is right-justified; a negative field size is left-justified.
The documentation is better on the Composite Formatting page of MSDN:
The optional alignment component is a signed integer indicating the
preferred formatted field width. If the value of alignment is less
than the length of the formatted string, alignment is ignored and the
length of the formatted string is used as the field width. The
formatted data in the field is right-aligned if alignment is positive
and left-aligned if alignment is negative. If padding is necessary,
white space is used. The comma is required if alignment is specified.

The number is the alignment, documented in the Alignment Component here.
The formatted data in the field is right-aligned if alignment is
positive and left-aligned if alignment is negative.
In your example, alignment will pad the p.ProcessName with spaces if it is less than 5 characters long. Where string length is less than the absolute value of alignment (like in your example), alignment has no effect.
Example
var text = "MyText";
Console.WriteLine($"x{text}x");
Console.WriteLine($"x{text, 3}x");
Console.WriteLine($"x{text, 10}x");
Console.WriteLine($"x{text, -10}x");
Result
xMyTextx
xMyTextx
x MyTextx
xMyText x

Related

C# Console table is not aligned

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.

Is it possible to configure Zebra labels to stop printing when the right edge of the label is reached?

The "description" part of the labels I'm printing are usually short like "super" and "superman", but once in while they are long like "supercalifragilisticexpealidocious"
In the latter case, the text wraps around, but does not "crlf", thus printing over portions of the original line.
crlif'ing would not be good, either, because that would "throw off" the alignment of the rest of the label.
I came up with a workaround to truncate the description if it's too long:
public void PrintLabel(string price, string description, string barcode)
{
const int MAX_CAPS_DESC_LEN = 21;
const int MAX_LOWERCASE_DESC_LEN = 32;
try
{
// Users were getting wrapped descriptions causing legibility/alignment
//problems; this code could be elegantized, but at the cost of readability
bool descAllUpper = HHSUtils.IsAllUpper(description);
if (descAllUpper)
{
if (description.Length > MAX_CAPS_DESC_LEN)
{
description = description.Substring(0, MAX_CAPS_DESC_LEN);
}
}
else // not all upper
{
if (description.Length > MAX_LOWERCASE_DESC_LEN)
{
description = description.Substring(0, MAX_LOWERCASE_DESC_LEN);
}
}
. . .
...but is there a way (a property/setting/configuration/command or such) that would tell the printer to stop at the edge of the label?
In windows > control panel > printers and devices, right click and printer properties. You can set margins and stuff. The zebra printers have lots of settings in there.
Also, we use smaller fonts to allowore characters, and uline.com sells 4x8 labels I believe instead of using standard 4x6.
Unfortunately, there is not an option for Text Field Word Wrap in the current Zebra Designer Software as of 2012-12-17 date. If you want to achieve this you must also add ZPL code into the PRN file as per the instructions taken from the ZPL Programming Manual Below.
EDIT: Had to indent all because stack was being weird.
Source Easyworks.com
Sample PRN File With and Without Code Code containing Word Wrap [highlighted in red]
CT~~CD,~CC^~CT~
^XA~TA000~JSN^LT0^MNW^MTD^PON^PMN^LH0,0^JMA^PR2,2~SD8^JUS^LRN^CI0^XZ
^XA
^MMT
^PW448
^LL0488
^LS0
^BY1,3,34^FT84,244^BCN,,Y,N
^FD>:<%EXP%>0^FS
^BY1,3,34^FT84,175^BCN,,Y,N
^FD>:<%UID%>0^FS
^BY1,3,34^FT84,106^BCN,,Y,N
^FD>:<%PARTNO%>0^FS
^FT84,344^AAN,27,15^FH\^FD<%EXP%>^FS
^FB500,3,,, //This is what the below is referencing
^FT84,293^AAN,18,10^FH\^FD<%WARN%>^FS
^PQ1,0,1,Y^XZ
Code Without Word Wrap
CT~~CD,~CC^~CT~
^XA~TA000~JSN^LT0^MNW^MTD^PON^PMN^LH0,0^JMA^PR2,2~SD8^JUS^LRN^CI0^XZ
^XA
^MMT
^PW448
^LL0488
^LS0
^BY1,3,34^FT84,244^BCN,,Y,N
^FD>:<%EXP%>0^FS
^BY1,3,34^FT84,175^BCN,,Y,N
^FD>:<%UID%>0^FS
^BY1,3,34^FT84,106^BCN,,Y,N
^FD>:<%PARTNO%>0^FS
^FT84,344^AAN,27,15^FH\^FD<%EXP%>^FS
^FT84,293^AAN,18,10^FH\^FD<%WARN%>^FS
^PQ1,0,1,Y^XZ
ZPL Programming Manual Excerpt Here is also an excerpt from the programming manual about the ^FB command
^FB - Field Block
Description The ^FB command allows you to print text into a defined block type format.
This command formats an ^FD or ^SN string into a block of text using the origin, font, and
rotation specified for the text string. The ^FB command also contains an automatic word-wrap function.
Format ^FBa,b,c,d,e
This table identifies the parameters for this format:
Parameters
a = width of text block line (in dots)
Accepted Values: 0 to the width of the label
Default Value: 0
If the value is less than font width or not specified, text does not print.
b = maximum number of lines in text block
Accepted Values: 1 to 9999
Default Value: 1
Text exceeding the maximum number of lines overwrites the last line. Changing the font size automatically increases or decreases the size of the block.
c = add or delete space between lines (in dots)
Accepted Values: -9999 to 9999
Default Value: 0
Numbers are considered to be positive unless preceded by a minus sign. Positive values add space; negative values delete space.
d = text justification Accepted Values:
L = left
C = center
R = right
J = justified
Default Value: L
If J is used the last line is left-justified.
e = hanging indent (in dots) of the second and remaining lines
Accepted Values: 0 to 9999
Default Value: 0
Comments on the ^FB Command This scheme can be used to facilitate special functions:
\& = carriage return/line feed
\(*) = soft hyphen (word break with a dash)
\\ = backslash (\)
Item 1: ^CI13 must be selected to print a backslash (\).
Item 2: If a soft hyphen escape sequence is placed near the end of a line, the hyphen is printed. If it is not placed near the end of the line, it is ignored.
(*) = any alphanumeric character
" If a word is too long to print on one line by itself (and no soft hyphen is specified), a hyphen is automatically placed in the word at the right edge of the block. The remainder of the word is on the next line. The position of the hyphen depends on word length, not a syllable boundary. Use a soft hyphen within a word to control where the hyphenation
occurs.
" Maximum data-string length is 3K, including control characters, carriage returns, and line feeds.
" Normal carriage returns, line feeds, and word spaces at line breaks are discarded.
" When using ^FT (Field Typeset), ^FTuses the baseline origin of the last possible line of text. Increasing the font size causes the text block to increase in size from bottom to top. This could cause a label to print past its top margin.
" When using ^FO (Field Origin), increasing the font size causes the text block to increase in size from top to bottom.
" ^FS terminates an ^FB command. Each block requires its own ^FB command.

Aligning string with spaces

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.

String.Format for Hex

With below code, the colorsting always gives #DDDD. Green, Red and Space values int he How to fix this?
string colorstring;
int Blue = 13;
int Green = 0;
int Red = 0;
int Space = 14;
colorstring = String.Format("#{0:X}{0:X}{0:X}{0:X}", Blue, Green, Red, Space);
The number 0 in {0:X} refers to the position in the list or arguments. In this case 0 means use the first value, which is Blue. Use {1:X} for the second argument (Green), and so on.
colorstring = String.Format("#{0:X}{1:X}{2:X}{3:X}", Blue, Green, Red, Space);
The syntax for the format parameter is described in the documentation:
Format Item Syntax
Each format item takes the following form and consists of the following components:
{ index[,alignment][:formatString]}
The matching braces ("{" and "}") are required.
Index Component
The mandatory index component, also called a parameter specifier, is a number starting from 0 that identifies a corresponding item in the list of objects. That is, the format item whose parameter specifier is 0 formats the first object in the list, the format item whose parameter specifier is 1 formats the second object in the list, and so on.
Multiple format items can refer to the same element in the list of objects by specifying the same parameter specifier. For example, you can format the same numeric value in hexadecimal, scientific, and number format by specifying a composite format string like this: "{0:X} {0:E} {0:N}".
Each format item can refer to any object in the list. For example, if there are three objects, you can format the second, first, and third object by specifying a composite format string like this: "{1} {0} {2}". An object that is not referenced by a format item is ignored. A runtime exception results if a parameter specifier designates an item outside the bounds of the list of objects.
Alignment Component
The optional alignment component is a signed integer indicating the preferred formatted field width. If the value of alignment is less than the length of the formatted string, alignment is ignored and the length of the formatted string is used as the field width. The formatted data in the field is right-aligned if alignment is positive and left-aligned if alignment is negative. If padding is necessary, white space is used. The comma is required if alignment is specified.
Format String Component
The optional formatString component is a format string that is appropriate for the type of object being formatted. Specify a standard or custom numeric format string if the corresponding object is a numeric value, a standard or custom date and time format string if the corresponding object is a DateTime object, or an enumeration format string if the corresponding object is an enumeration value. If formatString is not specified, the general ("G") format specifier for a numeric, date and time, or enumeration type is used. The colon is required if formatString is specified.
Note that in your case you only have the index and the format string. You have not specified (and do not need) an alignment component.
You can also pad the characters left by including a number following the X, such as this: string.format("0x{0:X8}", string_to_modify), which yields "0x00000C20".
Translate composed UInt32 color Value to CSS in .NET
I know the question applies to 3 input values (red green blue). But there may be the situation where you already have a composed 32bit Value. It looks like you want to send the data to some HTML CSS renderer (because of the #HEX format). Actually CSS wants you to print 6 or at least 3 zero filled hex digits here. so #{0:X06} or #{0:X03} would be required. Due to some strange behaviour, this always prints 8 digits instead of 6.
Solve this by:
String.Format("#{0:X02}{1:X02}{2:X02}", (Value & 0x00FF0000) >> 16, (Value & 0x0000FF00) >> 8, (Value & 0x000000FF) >> 0)
More generally.
byte[] buf = new byte[] { 123, 2, 233 };
string s = String.Concat(buf.Select(b => b.ToString("X2")));
If we have built in functions to convert your integer values to COLOR then why to worry.
string hexValue = string.Format("{0:X}", intColor);
Color brushes = System.Drawing.ColorTranslator.FromHtml("#"+hexValue);

Console.Write syntax: what does the format string "{0, -25}" mean

I am writing C# code
Console.Write("{0,-25}", company);
In above code what does this "{0,-25}" thing mean?
You mention it's hard to see what it does: that's because it adds spaces and those are difficult to see in the console. Try adding a character directly before and after the output so you can more clearly see the space, like the examples below:
This
Console.WriteLine("[{0, -25}]", "Microsoft"); // Left aligned
Console.WriteLine("[{0, 25}]", "Microsoft"); // Right aligned
Console.WriteLine("[{0, 5}]", "Microsoft"); // Ignored, Microsoft is longer than 5 chars
Will result in this (with spaces)
[Microsoft ]
[ Microsoft]
[Microsoft]
Which looks like this in the console window:
Read about string formatting on MSDN, specifically composite formatting. The '-25;' specifies the alignment component.
Alignment Component The optional alignment component is a signed
integer indicating the preferred formatted field width. If the value
of alignment is less than the length of the formatted string,
alignment is ignored and the length of the formatted string is used as
the field width. The formatted data in the field is right-aligned if
alignment is positive and left-aligned if alignment is negative. If
padding is necessary, white space is used. The comma is required if
alignment is specified.
That 'thing' is a composite formatting string. See the remarks here and this article here.
It is used for alignment.
Check this so that you can get
Console.Write("Company = |{0,-25}|", company);
string company1="ABC Inc";
string company2="XYZ International Inc";
Console.Write("{0,-10}", company1);//o/p [ABC Inc...]
Console.Write("{0,10}", company1);o/p [...ABC Inc]
Console.Write("{0,-10}", company2);o/p [XYZ International Inc]
//In the first Write(),output is LEFT justified in an output field width of 10
//In second Write(), output is RIGHT justified in an output field width of 10
//In the third Write(), output width is ignored , since the company2 name has more than 10 characters.

Categories