Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can maximum number of characters be defined in C# format strings like in C printf?

Tags:

Didn't find how to do that. What I found was more or less on the lines of this (http://blog.stevex.net/string-formatting-in-csharp/):

There really isn’t any formatting within a string, beyond it’s alignment. Alignment works for any argument being printed in a String.Format call. Sample Generates

String.Format(“->{1,10}<-”, “Hello”);  // gives "->     Hello<-" (left padded to 10) String.Format(“->{1,-10}<-”, “Hello”); // gives "->Hello     <-" (right padded to 10) 
like image 547
char m Avatar asked Nov 05 '10 11:11

char m


People also ask

How many characters can char hold in C?

For example, CHAR(30) can hold up to 30 characters. The length of a CHAR column is fixed to the length that you declare when you create the table. The length can be any value from 0 to 255.

What is the maximum length allowed in defining a variable in C?

ANSI standard recognizes a length of 31 characters for a variable name. However, the length should not be normally more than any combination of eight alphabets, digits, and underscores. 4. Uppercase and lowercase are significant.

What is the maximum number of char?

Numerically, the answer is 255. CHAR has a potential range of 0 to 255.

What is the maximum length of a string in C?

The maximum length of a string literal allowed in Microsoft C is approximately 2,048 bytes.


1 Answers

What you want is not "natively" supported by C# string formatting, as the String.ToString methods of the string object just return the string itself.

When you call

string.Format("{0:xxx}",someobject); 

if someobject implements the IFormattable interface, the overload ToString(string format,IFormatProvider formatProvider) method gets called, with "xxx" as format parameter.

So, at most, this is not a flaw in the design of .NET string formatting, but just a lack of functionality in the string class.

If you really need this, you can use any of the suggested workarounds, or create your own class implementing IFormattable interface.

like image 56
Paolo Tedesco Avatar answered Nov 02 '22 05:11

Paolo Tedesco