String.Format()方法

本文通过实例详细介绍了.NET中String.Format方法的使用技巧,包括数值、日期时间及枚举类型的格式化输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

String.Format方法是我们在.Net应用开发时经常使用到的,它的灵活使用有时能够达到事半功倍的效果,下面我们就借用MSDN上的一个示例来向大家展示String.Format的各种用法。

该示例展示了Numeric、DateTime和Enumeration标准格式的使用,另外,我们也可以根据需要自定义我们需要的格式。
 
 

// This code example demonstrates the String.Format() method.

using System;
class Sample 
{
    
enum Color {Yellow = 1, Blue, Green};

    
static DateTime thisDate = DateTime.Now;

    
public static void Main() 
    
{
        
// Store the output of the String.Format method in a string.
        string s = "";

        
// Format a negative integer or floating-point number in various ways.
        Console.WriteLine("Standard Numeric Format Specifiers");
        s 
= String.Format(
            
"(C) Currency: . . . . . . . . {0:C} " +
            
"(D) Decimal:. . . . . . . . . {0:D} " +
            
"(E) Scientific: . . . . . . . {1:E} " +
            
"(F) Fixed point:. . . . . . . {1:F} " +
            
"(G) General:. . . . . . . . . {0:G} " +
            
"    (default):. . . . . . . . {0} (default = 'G') " +
            
"(N) Number: . . . . . . . . . {0:N} " +
            
"(P) Percent:. . . . . . . . . {1:P} " +
            
"(R) Round-trip: . . . . . . . {1:R} " +
            
"(X) Hexadecimal:. . . . . . . {0:X} ",
            
-123-123.45f); 
        Console.WriteLine(s);

        
// Format the current date in various ways.
        Console.WriteLine("Standard DateTime Format Specifiers");
        s 
= String.Format(
            
"(d) Short date: . . . . . . . {0:d} " +
            
"(D) Long date:. . . . . . . . {0:D} " +
            
"(t) Short time: . . . . . . . {0:t} " +
            
"(T) Long time:. . . . . . . . {0:T} " +
            
"(f) Full date/short time: . . {0:f} " +
            
"(F) Full date/long time:. . . {0:F} " +
            
"(g) General date/short time:. {0:g} " +
            
"(G) General date/long time: . {0:G} " +
            
"    (default):. . . . . . . . {0} (default = 'G') " +
            
"(M) Month:. . . . . . . . . . {0:M} " +
            
"(R) RFC1123:. . . . . . . . . {0:R} " +
            
"(s) Sortable: . . . . . . . . {0:s} " +
            
"(u) Universal sortable: . . . {0:u} (invariant) " +
            
"(U) Universal sortable: . . . {0:U} " +
            
"(Y) Year: . . . . . . . . . . {0:Y} "
            thisDate);
        Console.WriteLine(s);

        
// Format a Color enumeration value in various ways.
        Console.WriteLine("Standard Enumeration Format Specifiers");
        s 
= String.Format(
            
"(G) General:. . . . . . . . . {0:G} " +
            
"    (default):. . . . . . . . {0} (default = 'G') " +
            
"(F) Flags:. . . . . . . . . . {0:F} (flags or integer) " +
            
"(D) Decimal number: . . . . . {0:D} " +
            
"(X) Hexadecimal:. . . . . . . {0:X} "
            Color.Green);       
        Console.WriteLine(s);
    }

}
 
以上代码的输出结果如下:
 
Standard Numeric Format Specifiers
(C) Currency: . . . . . . . . ¥-123.00
(D) Decimal:. . . . . . . . . -123
(E) Scientific: . . . . . . . -1.234500E+002
(F) Fixed point:. . . . . . . -123.45
(G) General:. . . . . . . . . -123
    (default):. . . . . . . . -123 (default = 'G')
(N) Number: . . . . . . . . . -123.00
(P) Percent:. . . . . . . . . -12,345.00%
(R) Round-trip: . . . . . . . -123.45
(X) Hexadecimal:. . . . . . . FFFFFF85
 
Standard DateTime Format Specifiers
(d) Short date: . . . . . . . 2007-1-29
(D) Long date:. . . . . . . . 2007年1月29日
(t) Short time: . . . . . . . 13:57
(T) Long time:. . . . . . . . 13:57:42
(f) Full date/short time: . . 2007年1月29日 13:57
(F) Full date/long time:. . . 2007年1月29日 13:57:42
(g) General date/short time:. 2007-1-29 13:57
(G) General date/long time: . 2007-1-29 13:57:42
    (default):. . . . . . . . 2007-1-29 13:57:42 (default = 'G')
(M) Month:. . . . . . . . . . 1月29日
(R) RFC1123:. . . . . . . . . Mon, 29 Jan 2007 13:57:42 GMT
(s) Sortable: . . . . . . . . 2007-01-29T13:57:42
(u) Universal sortable: . . . 2007-01-29 13:57:42Z (invariant)
(U) Universal sortable: . . . 2007年1月29日 5:57:42
(Y) Year: . . . . . . . . . . 2007年1月
 
Standard Enumeration Format Specifiers
(G) General:. . . . . . . . . Green
    (default):. . . . . . . . Green (default = 'G')
(F) Flags:. . . . . . . . . . Green (flags or integer)
(D) Decimal number: . . . . . 3
(X) Hexadecimal:. . . . . . . 00000003
 
<think>好的,用户问的是String.format方法的作用。我需要先解释清楚这个方法的基本功能,然后给出使用示例,这样用户能更好地理解。 首先,String.format用于格式化字符串,替换占位符。需要说明常见的占位符,比如%s、%d、%f等,以及它们的使用方式。可能用户是刚开始学Java,所以例子要简单明了。然后,用户可能想知道为什么用这个方法而不是字符串拼接。这时候需要对比两者的优缺点,比如可读性和性能上的优势。特别是处理多个变量时,格式化更清晰。 还要考虑国际化的问题,不同地区的数字和货币格式可能不同。可以提到使用Locale参数的方法,这样用户知道如何处理多语言环境。 接下来,用户可能遇到的问题包括格式错误,比如参数类型不匹配导致的异常。需要提醒注意事项,比如参数数量和类型要匹配,避免运行时错误。 最后,用户可能想知道实际应用场景,比如日志记录、用户界面显示等。举几个实际的例子,帮助他们理解何时使用这个方法。 相关问题方面,应该涵盖占位符列表、与拼接的区别、本地化处理、性能比较以及常见错误。这样用户可以进一步深入学习或解决相关问题。</think>`String.format` 是 Java 中用于格式化字符串的方法,其核心作用是 **将占位符替换为指定参数**,生成格式统一、可读性高的字符串。类似于 C 语言的 `printf`,但返回值为 `String`。 --- ### 基本语法 ```java String formattedString = String.format("格式模板", 参数1, 参数2, ...); ``` --- ### 常见占位符示例 | 占位符 | 作用 | 示例 | |--------|-----------------------|---------------------| | `%s` | 字符串 | `String.format("%s年%d月", 2024, 3)` → `"2024年3月"` | | `%d` | 整数(十进制) | `String.format("第%d名", 1)` → `"第1名"` | | `%f` | 浮点数 | `String.format("价格%.2f元", 9.99)` → `"价格9.99元"` | | `%c` | 字符 | `String.format("性别:%c", '男')` → `"性别:男"` | | `%b` | 布尔值 | `String.format("是否通过:%b", true)` → `"是否通过:true"` | | `%%` | 百分号(转义) | `String.format("折扣:%d%%", 85)` → `"折扣:85%"` | --- ### 核心优势 1. **可读性**:避免字符串拼接的冗余代码 ```java // 拼接写法 String s = "用户:" + name + ",年龄:" + age + ",余额:" + money + "元"; // 格式化写法 String s = String.format("用户:%s,年龄:%d,余额:%.2f元", name, age, money); ``` 2. **国际化支持**:自动适配本地化格式(如货币、千分位) ```java // 按美国格式输出:$1,234.57 String s = String.format(Locale.US, "金额:%,.2f", 1234.567); ``` 3. **格式控制**:对齐、补零、精度限制等高级操作 ```java // 右对齐并保留2位小数,宽度10: 3.14 String s = String.format("%10.2f", 3.1415); // 补零:007 String s = String.format("%03d", 7); ``` --- ### 注意事项 - **参数类型需匹配占位符**:若类型不匹配会抛出 `IllegalFormatConversionException`。 - **参数数量需匹配占位符数量**:缺少参数会抛出 `MissingFormatArgumentException`。 - **性能权衡**:频繁调用可能比 `StringBuilder` 略慢,但可读性优先。 --- ### 实际应用场景 1. **日志记录**:格式化输出时间、线程名、日志等级等。 2. **用户界面**:动态生成带变量的提示语(如 `"剩余%d秒"`)。 3. **数据导出**:按固定格式生成 CSV、JSON 字符串。 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值