当前位置: 首页>>代码示例>>C#>>正文


C# String.Format方法代码示例

本文整理汇总了C#中System.String.Format方法的典型用法代码示例。如果您正苦于以下问题:C# String.Format方法的具体用法?C# String.Format怎么用?C# String.Format使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.String的用法示例。


在下文中一共展示了String.Format方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1:

Decimal pricePerOunce = 17.36m;
String s = String.Format("The current price is {0} per ounce.",
                         pricePerOunce);
Console.WriteLine(s);
// Result: The current price is 17.36 per ounce.
开发者ID:.NET开发者,项目名称:System,代码行数:5,代码来源:String.Format

示例2:

Decimal pricePerOunce = 17.36m;
String s = String.Format("The current price is {0:C2} per ounce.",
                         pricePerOunce);
Console.WriteLine(s);
// Result if current culture is en-US:
//      The current price is $17.36 per ounce.
开发者ID:.NET开发者,项目名称:System,代码行数:6,代码来源:String.Format

示例3:

decimal temp = 20.4m;
string s = String.Format("The temperature is {0}°C.", temp);
Console.WriteLine(s);
// Displays 'The temperature is 20.4°C.'
开发者ID:.NET开发者,项目名称:System,代码行数:4,代码来源:String.Format

示例4:

string s = String.Format("At {0}, the temperature is {1}°C.",
                         DateTime.Now, 20.4);
Console.WriteLine(s);
// Output similar to: 'At 4/10/2015 9:29:41 AM, the temperature is 20.4°C.'
开发者ID:.NET开发者,项目名称:System,代码行数:4,代码来源:String.Format

示例5:

string s = String.Format("It is now {0:d} at {0:t}", DateTime.Now);
Console.WriteLine(s);
// Output similar to: 'It is now 4/10/2015 at 10:04 AM'
开发者ID:.NET开发者,项目名称:System,代码行数:3,代码来源:String.Format

示例6: for

int[] years = { 2013, 2014, 2015 };
     int[] population = { 1025632, 1105967, 1148203 };
     var sb = new System.Text.StringBuilder();
     sb.Append(String.Format("{0,6} {1,15}\n\n", "Year", "Population"));
     for (int index = 0; index < years.Length; index++)
        sb.Append(String.Format("{0,6} {1,15:N0}\n", years[index], population[index]));

     Console.WriteLine(sb);

     // Result:
     //      Year      Population
     //
     //      2013       1,025,632
     //      2014       1,105,967
     //      2015       1,148,203
开发者ID:.NET开发者,项目名称:System,代码行数:15,代码来源:String.Format

示例7: for

int[] years = { 2013, 2014, 2015 };
int[] population = { 1025632, 1105967, 1148203 };
String s = String.Format("{0,-10} {1,-10}\n\n", "Year", "Population");
for(int index = 0; index < years.Length; index++)
   s += String.Format("{0,-10} {1,-10:N0}\n",
                      years[index], population[index]);
Console.WriteLine($"\n{s}");
// Result:
//    Year       Population
//
//    2013       1,025,632
//    2014       1,105,967
//    2015       1,148,203
开发者ID:.NET开发者,项目名称:System,代码行数:13,代码来源:String.Format

示例8: DateTime

DateTime dat = new DateTime(2012, 1, 17, 9, 30, 0); 
string city = "Chicago";
int temp = -16;
string output = String.Format("At {0} in {1}, the temperature was {2} degrees.",
                              dat, city, temp);
Console.WriteLine(output);
开发者ID:.NET开发者,项目名称:System,代码行数:6,代码来源:String.Format

输出:

At 1/17/2012 9:30:00 AM in Chicago, the temperature was -16 degrees.

示例9: DateTime

// Create array of 5-tuples with population data for three U.S. cities, 1940-1950.
Tuple<string, DateTime, int, DateTime, int>[] cities = 
    { Tuple.Create("Los Angeles", new DateTime(1940, 1, 1), 1504277, 
                   new DateTime(1950, 1, 1), 1970358),
      Tuple.Create("New York", new DateTime(1940, 1, 1), 7454995, 
                   new DateTime(1950, 1, 1), 7891957),  
      Tuple.Create("Chicago", new DateTime(1940, 1, 1), 3396808, 
                   new DateTime(1950, 1, 1), 3620962),  
      Tuple.Create("Detroit", new DateTime(1940, 1, 1), 1623452, 
                   new DateTime(1950, 1, 1), 1849568) };

// Display header
var header = String.Format("{0,-12}{1,8}{2,12}{1,8}{2,12}{3,14}\n",
                              "City", "Year", "Population", "Change (%)");
Console.WriteLine(header);
foreach (var city in cities) {
   var output = String.Format("{0,-12}{1,8:yyyy}{2,12:N0}{3,8:yyyy}{4,12:N0}{5,14:P1}",
                          city.Item1, city.Item2, city.Item3, city.Item4, city.Item5,
                          (city.Item5 - city.Item3)/ (double)city.Item3);
   Console.WriteLine(output);
}
开发者ID:.NET开发者,项目名称:System,代码行数:21,代码来源:String.Format

输出:

City            Year  Population    Year  Population    Change (%)

Los Angeles     1940   1,504,277    1950   1,970,358        31.0 %
New York        1940   7,454,995    1950   7,891,957         5.9 %
Chicago         1940   3,396,808    1950   3,620,962         6.6 %
Detroit         1940   1,623,452    1950   1,849,568        13.9 %

示例10: foreach

short[] values= { Int16.MinValue, -27, 0, 1042, Int16.MaxValue };
Console.WriteLine("{0,10}  {1,10}\n", "Decimal", "Hex");
foreach (short value in values)
{
   string formatString = String.Format("{0,10:G}: {0,10:X}", value);
   Console.WriteLine(formatString);
}
开发者ID:.NET开发者,项目名称:System,代码行数:7,代码来源:String.Format

输出:

Decimal         Hex

-32768:       8000
-27:       FFE5
0:          0
1042:        412
32767:       7FFF

示例11: Main

//引入命名空间
using System;

public class TestFormatter
{
   public static void Main()
   {
      int acctNumber = 79203159;
      Console.WriteLine(String.Format(new CustomerFormatter(), "{0}", acctNumber));
      Console.WriteLine(String.Format(new CustomerFormatter(), "{0:G}", acctNumber));
      Console.WriteLine(String.Format(new CustomerFormatter(), "{0:S}", acctNumber));
      Console.WriteLine(String.Format(new CustomerFormatter(), "{0:P}", acctNumber));
      try {
         Console.WriteLine(String.Format(new CustomerFormatter(), "{0:X}", acctNumber));
      }
      catch (FormatException e) {
         Console.WriteLine(e.Message);
      }
   }
}

public class CustomerFormatter : IFormatProvider, ICustomFormatter
{
   public object GetFormat(Type formatType) 
   {
      if (formatType == typeof(ICustomFormatter))        
         return this; 
      else
         return null;
   }
   
   public string Format(string format, 
                         object arg, 
                         IFormatProvider formatProvider) 
   {                       
      if (! this.Equals(formatProvider))
      {
         return null;
      }
      else
      {
         if (String.IsNullOrEmpty(format)) 
            format = "G";
         
         string customerString = arg.ToString();
         if (customerString.Length < 8)
            customerString = customerString.PadLeft(8, '0');
         
         format = format.ToUpper();
         switch (format)
         {
            case "G":
               return customerString.Substring(0, 1) + "-" +
                                     customerString.Substring(1, 5) + "-" +
                                     customerString.Substring(6);
            case "S":                          
               return customerString.Substring(0, 1) + "/" +
                                     customerString.Substring(1, 5) + "/" +
                                     customerString.Substring(6);
            case "P":                          
               return customerString.Substring(0, 1) + "." +
                                     customerString.Substring(1, 5) + "." +
                                     customerString.Substring(6);
            default:
               throw new FormatException( 
                         String.Format("The '{0}' format specifier is not supported.", format));
         }
      }   
   }
}
开发者ID:.NET开发者,项目名称:System,代码行数:70,代码来源:String.Format

输出:

7-92031-59
7-92031-59
7/92031/59
7.92031.59
The 'X' format specifier is not supported.

示例12: GetFormat

//引入命名空间
using System;
using System.Globalization;

public class InterceptProvider : IFormatProvider, ICustomFormatter
{
   public object GetFormat(Type formatType)
   {
      if (formatType == typeof(ICustomFormatter))
         return this;
      else
         return null;
   }
   
   public string Format(String format, Object obj, IFormatProvider provider) 
   {
      // Display information about method call.
      string formatString = format ?? "<null>";
      Console.WriteLine("Provider: {0}, Object: {1}, Format String: {2}",
                        provider.GetType().Name, obj ?? "<null>", formatString);
                        
      if (obj == null) return String.Empty;
            
      // If this is a byte and the "R" format string, format it with Roman numerals.
      if (obj is Byte && formatString.ToUpper().Equals("R")) {
         Byte value = (Byte) obj;
         int remainder;
         int result;
         String returnString = String.Empty;

         // Get the hundreds digit(s)
         result = Math.DivRem(value, 100, out remainder);
         if (result > 0)  
            returnString = new String('C', result);
         value = (Byte) remainder;
         // Get the 50s digit
         result = Math.DivRem(value, 50, out remainder);
         if (result == 1)
            returnString += "L";
         value = (Byte) remainder;
         // Get the tens digit.
         result = Math.DivRem(value, 10, out remainder);
         if (result > 0)
            returnString += new String('X', result);
         value = (Byte) remainder; 
         // Get the fives digit.
         result = Math.DivRem(value, 5, out remainder);
         if (result > 0)
            returnString += "V";
         value = (Byte) remainder;
         // Add the ones digit.
         if (remainder > 0) 
            returnString += new String('I', remainder);
         
         // Check whether we have too many X characters.
         int pos = returnString.IndexOf("XXXX");
         if (pos >= 0) {
            int xPos = returnString.IndexOf("L"); 
            if (xPos >= 0 & xPos == pos - 1)
               returnString = returnString.Replace("LXXXX", "XC");
            else
               returnString = returnString.Replace("XXXX", "XL");   
         }
         // Check whether we have too many I characters
         pos = returnString.IndexOf("IIII");
         if (pos >= 0)
            if (returnString.IndexOf("V") >= 0)
               returnString = returnString.Replace("VIIII", "IX");
            else
               returnString = returnString.Replace("IIII", "IV");    

         return returnString; 
      }   

      // Use default for all other formatting.
      if (obj is IFormattable)
         return ((IFormattable) obj).ToString(format, CultureInfo.CurrentCulture);
      else
         return obj.ToString();
   }
}

public class Example
{
   public static void Main()
   {
      int n = 10;
      double value = 16.935;
      DateTime day = DateTime.Now;
      InterceptProvider provider = new InterceptProvider();
      Console.WriteLine(String.Format(provider, "{0:N0}: {1:C2} on {2:d}\n", n, value, day));
      Console.WriteLine(String.Format(provider, "{0}: {1:F}\n", "Today: ", 
                                      (DayOfWeek) DateTime.Now.DayOfWeek));
      Console.WriteLine(String.Format(provider, "{0:X}, {1}, {2}\n", 
                                      (Byte) 2, (Byte) 12, (Byte) 199));
      Console.WriteLine(String.Format(provider, "{0:R}, {1:R}, {2:R}\n", 
                                      (Byte) 2, (Byte) 12, (Byte) 199));
   }
}
开发者ID:.NET开发者,项目名称:System,代码行数:99,代码来源:String.Format

输出:

Provider: InterceptProvider, Object: 10, Format String: N0
Provider: InterceptProvider, Object: 16.935, Format String: C2
Provider: InterceptProvider, Object: 1/31/2013 6:10:28 PM, Format String: d
10: $16.94 on 1/31/2013

Provider: InterceptProvider, Object: Today: , Format String: 
Provider: InterceptProvider, Object: Thursday, Format String: F
Today: : Thursday

Provider: InterceptProvider, Object: 2, Format String: X
Provider: InterceptProvider, Object: 12, Format String: 
Provider: InterceptProvider, Object: 199, Format String: 
2, 12, 199

Provider: InterceptProvider, Object: 2, Format String: R
Provider: InterceptProvider, Object: 12, Format String: R
Provider: InterceptProvider, Object: 199, Format String: R
II, XII, CXCIX

示例13:

string[] names = { "Balto", "Vanya", "Dakota", "Samuel", "Koani", "Yiska", "Yuma" };
  string output = names[0] + ", " + names[1] + ", " + names[2] + ", " + 
                  names[3] + ", " + names[4] + ", " + names[5] + ", " + 
                  names[6];  

  output += "\n";  
  var date = DateTime.Now;
  output += String.Format("It is {0:t} on {0:d}. The day of the week is {1}.", 
                          date, date.DayOfWeek);
  Console.WriteLine(output);                           
  // The example displays the following output:
  //     Balto, Vanya, Dakota, Samuel, Koani, Yiska, Yuma
  //     It is 10:29 AM on 1/8/2018. The day of the week is Monday.
开发者ID:.NET开发者,项目名称:System,代码行数:13,代码来源:String.Format

示例14:

string[] names = { "Balto", "Vanya", "Dakota", "Samuel", "Koani", "Yiska", "Yuma" };
  string output = $"{names[0]}, {names[1]}, {names[2]}, {names[3]}, {names[4]}, " + 
                  $"{names[5]}, {names[6]}";  

  var date = DateTime.Now;
  output += $"\nIt is {date:t} on {date:d}. The day of the week is {date.DayOfWeek}.";
  Console.WriteLine(output);                           
  // The example displays the following output:
  //     Balto, Vanya, Dakota, Samuel, Koani, Yiska, Yuma
  //     It is 10:29 AM on 1/8/2018. The day of the week is Monday.
开发者ID:.NET开发者,项目名称:System,代码行数:10,代码来源:String.Format

示例15: foreach

object[] values = { 1603, 1794.68235, 15436.14 };
string result;
foreach (var value in values) {
   result = String.Format("{0,12:C2}   {0,12:E3}   {0,12:F4}   {0,12:N3}  {1,12:P2}\n",
                          Convert.ToDouble(value), Convert.ToDouble(value) / 10000);
   Console.WriteLine(result);
}
开发者ID:.NET开发者,项目名称:System,代码行数:7,代码来源:String.Format

输出:

$1,603.00     1.603E+003      1603.0000      1,603.000       16.03 %

$1,794.68     1.795E+003      1794.6824      1,794.682       17.95 %

$15,436.14     1.544E+004     15436.1400     15,436.140      154.36 %


注:本文中的System.String.Format方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。