Im new to C# programming. Can someone please explain the following code:
Console.WriteLine( "{0}{1,10}", "Face", "Frequency" ); //Headings
Console.WriteLine( "{0,4}{1,10}",someval,anotherval);
I understand that this prints two columns of values with the headings given, and {0} refers to the first argument given. But what is the meaning of the format strings of the form {x,y} ?
It adds padding to the left. Very useful for remembering the various string formatting patterns is the following cheat sheet:
.NET String.Format Cheat Sheet
Positive values add padding to the left, negative add padding to the right
Sample Generates
String.Format("[{0, 10}]", "Foo"); [∙∙∙∙∙∙∙Foo]
String.Format("[{0, 5}]", "Foo"); [∙∙Foo]
String.Format("[{0, -5}]", "Foo"); [Foo∙∙]
String.Format("[{0, -10}]", "Foo"); [Foo∙∙∙∙∙∙∙]
When you see {x,y}, x represents the argument's index and y the alignment, as specified here. The complete syntax is the following:
{index[,alignment][:formatString]}
This is a padding value...if the argument isn't the length that is specified, it puts spaces in.
E.g. if you had {0,10} and the argument for {0} was "Blah", the actual value printed would be "Blah<SPACE><SPACE><SPACE><SPACE><SPACE><SPACE>"...Blah, with 6 extra spaces to make up a string of 10 length
ps - not sure how to put actual spaces in...need to look up SO faq no doubt
Related
I tried to figure out the basics of these numeric string formatters. So I think I understand the basics but there is one thing I'm not sure about
So, for example
#,##0.00
It turns out that it produces identical results as
#,#0.00
or
#,0.00
#,#########0.00
So my question is, why are people using the #,## so often (I see it a lot when googling)
Maybe I missed something.
You can try it out yourself here and put the following inside that main function
double value = 1234.67890;
Console.WriteLine(value.ToString("#,0.00"));
Console.WriteLine(value.ToString("#,#0.00"));
Console.WriteLine(value.ToString("#,##0.00"));
Console.WriteLine(value.ToString("#,########0.00"));
Probably because Microsoft uses the same format specifier in their documentation, including the page you linked. It's not too hard to figure out why; #,##0.00 more clearly states the programmer's intent: three-digit groups separated by commas.
What happens?
The following function is called:
public string ToString(string? format)
{
return Number.FormatDouble(m_value, format, NumberFormatInfo.CurrentInfo);
}
It is important to realize that the format is used to format the string, but your formats happen to give the same result.
Examples:
value.ToString("#,#") // 1,235
value.ToString("0,0") // 1,235
value.ToString("#") // 1235
value.ToString("0") // 1235
value.ToString("#.#")) // 1234.7
value.ToString("#.##") // 1234.68
value.ToString("#.###") // 1234.679
value.ToString("#.#####") // 1234.6789
value.ToString("#.######") // = value.ToString("#.#######") = 1234.6789
We see that
it doesn't matter whether you put #, 0, or any other digit for that matter
One occurrence means: any arbitrary large number
double value = 123467890;
Console.WriteLine(value.ToString("#")); // Prints the full number
, and . however, are treated different for double
After a dot or comma, it will only show the amount of character that are provided (or less: as for #.######).
At this point it's clear that it has to do with the programmer's intent. If you want to display the number as 1,234.68 or 1234.67890, you would format it as
"#,###.##" or "#,#.##" // 1,234.68
"####.#####" or "#.#####" // 1234.67890
I know that the following syntax works
String.Format("Today is {0}, {1}", day,month);
I was just curious how this format works?
String.Format("Today is {day}, {month}", day,month);
How does C# interpret replacing number with user defined names?
String.Format("Today is {day}, {month}", day,month);
Does not work, it throws a System.FormatException.
According to the documentation the replacement fields must be in the format { index[,alignment][:formatString]} which your 2nd example does not follow.
The items in the {} must be integers beginning at 0 and match the number of variables in the second argument of .Format(...) method. Download a program, such as LinqPad, to run test scripts such as this.
Ok so basically I want something like
Console.WriteLine(
"{0}: {1}/{2}hp {3}/{4}mp {5}",
character.Identifier,
character.CurrentHealth,
character.MaxHealth,
character.CurrentMagic,
character.MaxMagic,
character.Fatigue
);
and then have the character.Identifier (which is basically a name) have a set number of letters which it will replace with spaces if needed so that in might print
Josh: 20/20hp 20/20mp 3
or
J: 20/20hp 20/20mp 3
but the HP and then mp and everything else is always in line.
I am aware that its probably one of the {0:} but i couldn't figure out one that works
The second argument in the {0} notation can give you a fixed width field, so if you wanted the identifier (name) to always be 10 characters long and be left justified, you would use {0,-10}
MSDN is a good resource for this kind of question too, if you read the documentation for String.Format it has an example of a fixed width table that might be similar to what you want.
Also, as Hogan's answer correctly points out, you would have to append the : to the string outside of the format string if you want it right next to the name.
You can right pad a string with spaces by using:
character.Identifier.PadRight(10);
This should give you the format you are after.
I believe this will do what you want:
const int colWidth = 10;
Console.WriteLine("{0,-"+colWidth.ToString()+"}{1,-"+colWidth.ToString()+"}{2,-"+colWidth.ToString()+"}{3}",
(character.Identifier+":").PadRight(colWidth+1).Remove(0,colWidth),
(character.CurrentHealth+"/"+character.MaxHealth+"hp").PadRight(colWidth+1).Remove(0,colWidth),
(character.CurrentMagic+"/"+character.MaxMagic+"mp").PadRight(colWidth+1).Remove(0,colWidth),
(character.Fatigue,colWidth));
This will add spaces to the end of string and then truncate the result.
See the docs for String.Format
NOTES
I append the : to the name outside of the format string and I "merge" the hp and mp sections and then put them in a column.
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.
I'm trying to add commas to the following line of code:
Console.WriteLine(String.Format("{0, 8} {1,8} {2,8}", number, square,
cube));
How does one use alignment formatting in conjunction with adding commas?
It's this way
{0,8:N2}
N2 will format with comma based on locale.
Output sample could be useful... This: String.Format("{0, 8}, {1,8}, {2,8}", number, square, cube)); ?
Or you are looking for Number formatting that has thousands separator? Than you need to specify desired CultureInfo as first argument of the String.Format.
Try adding in the commas to the numbers before performing the alignment formatting (modifying based on your locale/culture, if necessary):
Console.WriteLine(
String.Format("{0, 8} {1,8} {2,8}",
number.ToString("#,0"),
square.ToString("#,0"),
cube.ToString("#,0")
)
);
And as Jeff points out in his comment below, you can also accomplish this by including the comma formats inline with the alignment formatting (the first part of each format block gives the alignment, the second part formats the string):
Console.WriteLine("{0,8:#,0} {1,8:#,0} {2,8:#,0}", number, square, cube);