C#的String.Format 方法

目录

一、重载

二、Format(String, Object)

1.定义 

2.示例

三、Format(String, Object[])

1.定义

2.示例

3.示例 


        将对象的值转换为基于指定格式的字符串,并将其插入到另一个字符串。

一、重载

Format(IFormatProvider, String, Object, Object, Object)

将字符串中的格式项替换为三个指定对象的字符串表示形式。 参数提供区域性特定的格式设置信息。

Format(String, Object, Object, Object)

将字符串中的格式项替换为三个指定对象的字符串表示形式。

Format(IFormatProvider, String, Object, Object)

将字符串中的格式项替换为两个指定对象的字符串表示形式。 参数提供区域性特定的格式设置信息。

Format(String, Object, Object)

将字符串中的格式项替换为两个指定对象的字符串表示形式。

Format(IFormatProvider, CompositeFormat, ReadOnlySpan)

将 中的 CompositeFormat 一个或多个格式项替换为指定格式的相应对象的字符串表示形式。

Format(IFormatProvider, String, Object)

将指定字符串中的一个或多个格式项替换为对应对象的字符串表示形式。 参数提供区域性特定的格式设置信息。

Format(IFormatProvider, String, Object[])

将字符串中的格式项替换为指定数组中相应对象的字符串表示形式。 参数提供区域性特定的格式设置信息。

Format(String, Object[])

将指定字符串中的格式项替换为指定数组中相应对象的字符串表示形式。

Format(String, Object)

将字符串中的一个或多个格式项替换为指定对象的字符串表示形式。

Format(IFormatProvider, CompositeFormat, Object[])

将 中的 CompositeFormat 一个或多个格式项替换为指定格式的相应对象的字符串表示形式。

Format(IFormatProvider, CompositeFormat, TArg0, TArg1, TArg2)

将 中的 CompositeFormat 一个或多个格式项替换为指定格式的相应对象的字符串表示形式。

Format(IFormatProvider, CompositeFormat, TArg0, TArg1)

将 中的 CompositeFormat 一个或多个格式项替换为指定格式的相应对象的字符串表示形式。

Format(IFormatProvider, CompositeFormat, TArg0)

将 中的 CompositeFormat 一个或多个格式项替换为指定格式的相应对象的字符串表示形式。

二、Format(String, Object)

        将字符串中的一个或多个格式项替换为指定对象的字符串表示形式。

1.定义 

public static string Format (string format, object? arg0);

参数
format    String
复合格式字符串。

arg0    Object
要设置格式的对象。

返回
String
format 的副本,其中的任何格式项均替换为 arg0 的字符串表示形式。

例外
ArgumentNullException
format 为 null。

FormatException
format 中的格式项无效。
或
格式项的索引不为零。

2.示例

        使用 Format(String, Object) 方法在输出的字符串中间嵌入个人的年龄(指定的字符串)。

// 使用 Format(String, Object) 方法在输出的字符串中间嵌入个人的年龄
namespace _068_6
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            ArgumentNullException.ThrowIfNull(args);
           
            DateTime birthday = new(1969, 1, 12);
            DateTime[] dates = [ new(1969, 11, 12),
                     new DateTime(1994, 10, 1),
                     new DateTime(2000, 10, 16),
                     new DateTime(2003, 7, 27),
                     new DateTime(2024, 1, 29) ];

            foreach (DateTime date in dates)
            {
                TimeSpan interval = date - birthday;
                // Get the approximate number of years, without accounting for leap years.
                int years = (int)interval.TotalDays / 365;
                // See if adding the number of years exceeds dateValue.
                string output;
                if (birthday.AddYears(years) <= date)
                {
                    output = string.Format("You are now {0} years old.", years);
                    Console.WriteLine(output);
                }
                else
                {
                    output = string.Format("You are now {0} years old.", years - 1);
                    Console.WriteLine(output);
                }
            }
        }
    }
}
// 运行结果:
/*
You are now 0 years old.
You are now 25 years old.
You are now 31 years old.
You are now 34 years old.
You are now 55 years old.

 */

        示例中出现的DateTime对象的AddYears()方法详见本文作者发布的其他文章。

三、Format(String, Object[])

        将指定字符串中的格式项替换为指定数组中相应对象的字符串表示形式。

1.定义

public static string Format (string format, params object?[] args);

参数
format    String
复合格式字符串。

args    Object[]
一个对象数组,其中包含零个或多个要设置格式的对象。

返回
String
format 的副本,其中格式项已替换为 args 中相应对象的字符串表示形式。

例外
ArgumentNullException
format 或 args 为 null。

FormatException
format 无效。
或
格式项的索引小于零,或者大于或等于 args 数组的长度。

2.示例

        创建一个字符串,其中包含特定日期的高温和低温数据。 有五个格式项,其中两个格式项定义其相应值字符串表示形式的宽度,第一个格式项还包括标准日期和时间格式字符串。

// Format(String, Object[])
namespace _068_7
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            ArgumentNullException.ThrowIfNull(args);

            DateTime date1 = new(2024, 1, 28);
            TimeSpan hiTime = new(14, 17, 32);
            decimal hiTemp = 62.1m; //decimal是数据类型,就像string一样,创建时在数字后面加m
            TimeSpan loTime = new(3, 16, 10);
            decimal loTemp = 54.8m;

            string result1 = string.Format("Temperature on {0:d}:\n{1,11}: {2} degrees (hi)\n{3,11}: {4} degrees (lo)",
                                           date1, hiTime, hiTemp, loTime, loTemp);
            Console.WriteLine(result1);
            Console.WriteLine("******************************");

            string result2 = string.Format("Temperature on {0:d}:\n{1,11}: {2} degrees (hi)\n{3,11}: {4} degrees (lo)",
                                           new object[] { date1, hiTime, hiTemp, loTime, loTemp });
            Console.WriteLine(result2);
        }
    }
}
// 运行结果:
/*
Temperature on 2024/1/28:
   14:17:32: 62.1 degrees (hi)
   03:16:10: 54.8 degrees (lo)
******************************
Temperature on 2024/1/28:
   14:17:32: 62.1 degrees (hi)
   03:16:10: 54.8 degrees (lo)

 */

        示例中出现的decimal是数据类型,它的用法就好比string类型的使用。定义一个decimal类型的变量时,必须在赋的值后面加m,否则警告double类型不能转为decimal类型。

3.示例 

// Format(String, Object[])
// 传递要格式化输出的数组而不是参数列表的对象。
namespace _068_8
{
    public class Example
    {
        public static void Main()
        {
            CityInfo newyork2024 = new("New York", 8175133, 302.64m, 2024);
            ShowPopulationData(newyork2024);
            CityInfo seattle2024 = new("Seattle", 608660, 83.94m, 2024);
            ShowPopulationData(seattle2024);
        }
        /// 
        ///  {2:N0}代表参数2,数字,小数位0;
        ///  {3:N1}代表参数3,数字,小数位1;
        /// 
        private static void ShowPopulationData(CityInfo city)
        {
            object[] args = [city.Name!, city.Year!, city.Population!, city.Area!];
            string result = string.Format("{0} in {1}: Population {2:N0}, Area {3:N1} sq. feet",args);
            Console.WriteLine(result);
        }
    }
}
// 运行结果:
/*
New York in 2024: Population 8,175,133, Area 302.6 sq. feet
Seattle in 2024: Population 608,660, Area 83.9 sq. feet

 */

        其它的重载方法的示例暂时不发布。

你可能感兴趣的:(c#,java,前端)