Wednesday, December 08, 2004

How do I write out a curly bracket in string formats?

Kit George azt mondja a gotdodnet-en:

If you're trying to format some value inside literal curly brackets, then we suggest:

  • If you don't need to justify the result, use String.Format("{{{0}}}", variable.ToString(formatSpecifier))
  • If you need to justify the result, use String.Format("{0,-7:{{customFormat}}}", variable), where customFormat is an appropriate custom format

Azert van 2 hiba cikkben:
1: azt mondja, hogy ez a sor:
string s = String.Format("{0}{1}{2}", "{", i, "}");
eredmenykent '{42.00}'-t ad, de kozben az eredmeny '{42}' lesz

2: azt mondja, hogy ez a sor:
//string s = String.Format("{{{0,-7:N}}}", i);
eredmenykent '{42.00 }'-t ad, de kozben az eredmeny '{N}' lesz

Na de ami igazan fontos:
When providing a format specifier, string formatting takes these steps:
  • Determine if the specifier is longer than a single character: if so, then assume that the specifier is a custom format. A custom format will use suitable replacements for your format, but if it doesn't know what to do with some character, it will simply write it out as a literalliterals found in the format
  • Determine if the single character specifier is a supported specifier (such as 'N' for number formatting). If it is, then format appropriately. If not, throw an ArgumentException

No comments: