GOOD formating in VBNET
String.Format("{0}", "formatting string"};
One of the painful things about good old ASP was string formatting, VBScript simply didn't have anything useful. C# (and VB.Net) do, but MSDN doesn't provide a quick reference to the formatting options. So here's a quick reference.
To compare string formatting in C# to those in C lets have an example,
char szOutput[256];
sprintf(szOutput, "At loop position %d.\n", i);
sprintf takes an output buffer, a format string and any number of arguments to substitute into the format string.
The C# equivalent for sprintf is String.Format, which takes a format string and the arguments. It returns a string, and because you're not passing in a buffer there's no chance of a buffer overflow.
string outputString = String.Format("At loop position {0}.\n", i);
So why doesn't have the format argument have parameters specifying what data type you're formatting? The CLR objects have metadata which informs the CLR what the objects are, and each object has a standard ToString() method which returns a string representation of that object. Much nicer than C where if you passed the wrong type of variable into sprintf everything could come crashing down.
The ToString method can accept a string parameter which tells the object how to format itself. In the call to String.Format , the formatting string is passed after the position, for example, "{0:##}". The text inside the curly braces is {argumentIndex[,alignment][:formatString]}. If alignment is positive, the text is right-padding to fill the specified field length, if it's negative, it's left-padded.
formatting strings
There's not much formatting that can be applied to a string. Only the padding / alignment formatting options can be applied. These options are also available to every argument, regardless of type.
example
output
String.Format("--{0,10}--", "test");
-- test--
String.Format("--{0,-10}--", "test");
--test --
formatting numbers
....
No comments:
Post a Comment