string.format()

本文介绍了使用C#中的String.Format方法来格式化字符串、数字和日期的方法。涵盖了预定义和自定义格式选项,包括数字的货币、指数、固定小数点等格式,以及日期的短日期、长日期、完整日期时间等格式。
Zeichenketten und Datumswerte formatieren

Oft kommt es vor, dass man Zeichenketten und Datumswerte in einem bestimmten Format ausgeben muss. Das Microsoft Framework stellt eine mächte Methode zur Verfügung mit der man einfach und schnell Formatvorlagen auf Zeichenketten oder Datumswerte anwenden kann: String.Format().

Im folgenden findet man die wichtigtens Formate:

FormatAufrufErgebnis
Zahlen mit vordefiniertem Format formatieren (zahl = 1000000)
cString.Format("{0:c}", zahl)1.000.000.00 ?
dString.Format("{0:d}", zahl)1000000
eString.Format("{0:e}", zahl)1000000e+006
fString.Format("{0:f}", zahl)1000000,00
gString.Format("{0:g}", zahl)1000000
nString.Format("{0:n}", zahl)1.000.000.00
xString.Format("{0:x}", zahl)f4240
Zahlen mit eigenem Format formatieren (zahl = 1000000)
0String.Format("{0:00.0000}", zahl)1000000,0000
#String.Format("{0:(#).##}", zahl)(1000000)
.String.Format("{0:0.0}", zahl)1000000,0
,String.Format("{0:0,0}", zahl)1.000.000
,.String.Format("{0:0,.}", zahl)1000
%String.Format("{0:0%}", zahl)100000000%
eString.Format("{0:00e+0}", zahl)10e+5
 
Datum mit vordefiniertem Format formatieren
uString.Format("{0:u}", DateTime.Now)2003-12-03 14:43:36Z
UString.Format("{0:U}", DateTime.Now)Mittwoch, 3. Dezember 2003 13:43:36
rString.Format("{0:r}", DateTime.Now)Wed, 03 Dec 2003 14:43:36 GMT
sString.Format("{0:s}", DateTime.Now)2003-12-03T14:43:36
YString.Format("{0:Y}", DateTime.Now)Dezember 2003
gString.Format("{0:g}", DateTime.Now)03.12.2003 14:43
GString.Format("{0:G}", DateTime.Now)03.12.2003 14:43:36
MString.Format("{0:M}", DateTime.Now)03 Dezember
dString.Format("{0:d}", DateTime.Now)03.12.2003
DString.Format("{0:D}", DateTime.Now)Mittwoch, 3. Dezember 2003
tString.Format("{0:t}", DateTime.Now)14:43
TString.Format("{0:T}", DateTime.Now)14:43:36
fString.Format("{0:f}", DateTime.Now)Mittwoch, 3. Dezember 2003 14:43
FString.Format("{0:F}", DateTime.Now)Mittwoch, 3. Dezember 2003 14:43:36
Datum mit eigenem Format formatieren
ddString.Format("{0:F}", DateTime.Now)03
dddString.Format("{0:F}", DateTime.Now)Mi
ddddString.Format("{0:F}", DateTime.Now)Mittwoch
MMString.Format("{0:F}", DateTime.Now)12
MMMString.Format("{0:F}", DateTime.Now)Dez
MMMMString.Format("{0:F}", DateTime.Now)Dezember
yyString.Format("{0:F}", DateTime.Now)03
yyyyString.Format("{0:F}", DateTime.Now)2003
ssString.Format("{0:F}", DateTime.Now)36
mmString.Format("{0:F}", DateTime.Now)43
hhString.Format("{0:F}", DateTime.Now)02
HHString.Format("{0:F}", DateTime.Now)14
ggString.Format("{0:F}", DateTime.Now)n. Chr.
ttString.Format("{0:F}", DateTime.Now)
zzString.Format("{0:F}", DateTime.Now)+01
zzzString.Format("{0:F}", DateTime.Now)+01:00

第二部分:

String.Format("{0}", "formatting string"};
Tue, 14 Jul 2004 19:30:00 GMT
One of the painful things about good old ASP was string formatting, VBScript simply didn't have anything useful. C# (and VB.Net) do, but MSDN doesn't provide a quick reference to the formatting options. So here's a quick reference.

To compare string formatting in C# to those in C lets have an example,

char szOutput[256];
sprintf(szOutput, "At loop position %d./n", i);


sprintf takes an output buffer, a format string and any number of arguments to substitute into the format string.

The C# equivalent for sprintf is String.Format, which takes a format string and the arguments. It returns a string, and because you're not passing in a buffer there's no chance of a buffer overflow.

string outputString = String.Format("At loop position {0}./n", i);


So why doesn't have the format argument have parameters specifying what data type you're formatting? The CLR objects have metadata which informs the CLR what the objects are, and each object has a standard ToString() method which returns a string representation of that object. Much nicer than C where if you passed the wrong type of variable into sprintf everything could come crashing down.

The ToString method can accept a string parameter which tells the object how to format itself. In the call to String.Format , the formatting string is passed after the position, for example, "{0:##}". The text inside the curly braces is {argumentIndex[,alignment][:formatString]}. If alignment is positive, the text is right-padding to fill the specified field length, if it's negative, it's left-padded.

formatting strings
There's not much formatting that can be applied to a string. Only the padding / alignment formatting options can be applied. These options are also available to every argument, regardless of type.

example output
String.Format("--{1,10}--", "test"); --      test--
String.Format("--{1,-10}--", "test"); --test      --


formatting numbers
Number formatting is culture dependant. For example, formatting a currency string on my laptop will return a result like £9.99, formatting a currency on a machine set for the US region would return $9.99.

specifier type format output
(double 1.2345) output
(int -12345)
c currency {0:c} £1.23 -£12,345.00
d decimal
(whole number) {0:d} System.FormatException -12345
e exponent / scientific {0:e} 1.234500e+000 -1.234500e+004
f fixed point {0:f} 1.23 -12345.00
g general {0:g} 1.2345 -12345
n number {0:n} 1.23 -12,345.00
r round trippable {0:r} 1.23 System.FormatException
x hexadecimal {0:x4} System.FormatException ffffcfc7


custom number formatting
specifier type format output
(double 1234.56)
0 zero placeholder {0:00.000} 1234.560
# digit placeholder {0:#.##} 1234.56
. decimal point placeholder {0:0.0} 1234.6
, thousand separator {0:0,0} 1,235
% percentage {0:0%} 123456%


In addition there is the group separator; this is useful for varying the format, depending on the value of the parameter passed. For example

String.Format("{0:£#,##0.00;(£#,##0.00);Nothing}", value);


This will output "£1,240.00" if passed 1243.56.  It will output the same format bracketed if the value is negative "(£1,240.00)", and will output the string "Nothing" if the number is zero.

date formatting
Date formats are very dependant on the culture information passed. The examples below are shown using the UK culture.

specifier type output
(June 8, 1970 12:30:59)
d Short Date 08/06/1970
D Long Date 08 June 1970
t Short Time 12:30
T Long Time 12:30:59
f Full date and time 08 June 1970 12:30
F Full date and time (long) 08 June 1970 12:30:59
g Default date and time 08/06/1970 12:30
G Default date and time (long) 08/06/1970 12:30:59
M Day / Month 8 June
r RFC1123 date string Mon, 08 Jun 1970 12:30:59 GMT
s Sortable date/time 1970-06-08T12:30:59
u Universal time, local timezone 1970-06-08 12:30:59Z
Y Month / Year June 1970


custom date formatting
specifier type output
(June 8, 1970 12:30:59)
dd Day 08
ddd Short Day Name Mon
dddd Full Day Name Monday
hh 2 digit hour 12
HH 2 digit hour (24 hour) 12
mm 2 digit minute 30
MM Month 06
MMM Short Month name Jun
MMMM Month name June
ss seconds 59
tt AM/PM PM
yy 2 digit year 70
yyyy 4 digit year 1970
: seperator, e.g. {0:hh:mm:ss} 12:30:59
/ seperator, e.g. {0:dd/mm/yyyy} 08/06/1970


There are others, including time zone formatting and so on, but the ones above are the most commonly used.

culture information
string.format also provides a method which accepts a CultureInfo argument, as an IFormatProvider. This is important when trying to write portable and localisable code, as, for example, month names will change according to the local culture of the machine you are running on. Rather than simply call the standard String.Format you should consider always calling the overloaded culture method. If you don't need to specify a culture you can use the System.Globalization.CultureInfo.InvariantCulture. This will then default your formatting to English, as opposed to the culture of the current thread.



Trackback: http://tb.blog.youkuaiyun.com/TrackBack.aspx?PostId=479426 

<think>我们正在讨论Lua的string.format函数。根据引用,我们知道这个函数用于格式化字符串,比使用".."操作符连接字符串在某些情况下更灵活和可读,尤其是当需要特定格式转换(如十六进制、补零等)时。 函数定义: string.format(formatstring, ...) 第一个参数是格式字符串,包含占位符(如%d, %s等),后续参数用于替换这些占位符。 常用占位符: %d - 整数 %f - 浮点数 %s - 字符串 %x - 十六进制(小写字母) %X - 十六进制(大写字母) %% - 百分号本身 特殊格式控制(以%d为例): %02d - 表示整数至少显示两位,不足两位在前面补0 %-3d - 表示左对齐,宽度为3,不足用空格填充 示例: 1. 整数补零:string.format("%02d", 1) -> "01" 2. 左对齐:string.format("%-3d", 22) -> "22 "(后面有一个空格) 虽然string.format在性能上可能比".."稍差(因为它调用了C函数),但在复杂格式化时提高了可读性。 下面我们通过一些示例来详细说明用法。</think>### Lua `string.format` 字符串格式化详解 `string.format()` 是 Lua 中用于格式化字符串的核心函数,特别适合处理复杂格式或需要特定转换的场景。相比简单的 `..` 连接操作,它提供更强大的格式化能力[^1][^2]。 #### 基本语法 ```lua local result = string.format(format_string, arg1, arg2, ...) ``` - **format_string**:包含占位符的格式字符串 - **arg1, arg2...**:替换占位符的实际值 #### 常用占位符 | 占位符 | 说明 | 示例 | 输出结果 | |--------|---------------------|--------------------------|----------------| | `%d` | 十进制整数 | `string.format("%d", 25)`| `"25"` | | `%f` | 浮点数 | `string.format("%.2f", math.pi)` | `"3.14"` | | `%s` | 字符串 | `string.format("Hello %s", "Lua")` | `"Hello Lua"` | | `%x` | 十六进制(小写) | `string.format("%x", 255)` | `"ff"` | | `%X` | 十六进制(大写) | `string.format("%X", 255)` | `"FF"` | | `%%` | 百分号本身 | `string.format("50%% off")` | `"50% off"` | #### 高级格式控制 1. **数字补零**(固定位数显示): ```lua print(string.format("ID: %03d", 7)) -- ID: 007 print(string.format("Hex: %04X", 15)) -- Hex: 000F ``` 2. **对齐控制**: ```lua -- 左对齐(宽度10) print(string.format("|%-10s|", "Lua")) -- |Lua | -- 右对齐(宽度10) print(string.format("|%10s|", "Lua")) -- | Lua| ``` 3. **浮点数精度**: ```lua print(string.format("Pi: %.4f", math.pi)) -- Pi: 3.1416 print(string.format("Ratio: %.1f%%", 85.32)) -- Ratio: 85.3% ``` 4. **多参数组合**: ```lua local name, age = "Alice", 30 local msg = string.format("%s is %d years old (%02d/%02d)", name, age, 5, 3) -- Alice is 30 years old (05/03) ``` #### 性能注意事项 虽然 `string.format()` 比 `..` 连接操作性能稍低(底层调用 C 函数 `str_format`)[^3],但在以下场景仍推荐使用: - 需要数字格式化(补零、十六进制转换等) - 长字符串拼接(提高可读性) - 需要精确控制输出格式时 ```mermaid graph LR A[字符串格式化需求] --> B{简单拼接?} B -->|是| C[使用 .. 操作符] B -->|否| D{需要特殊格式?} D -->|是| E[使用 string.format] D -->|否| F[考虑 table.concat] ``` #### 实际应用示例 ```lua -- 表格数据格式化输出 local data = { { "Apple", 2.49, 10 }, { "Banana", 1.29, 25 }, { "Orange", 3.99, 8 } } for _, item in ipairs(data) do print(string.format("| %-10s | $%5.2f | %03d |", item[1], item[2], item[3])) end -- 输出: -- | Apple | $ 2.49 | 010 | -- | Banana | $ 1.29 | 025 | -- | Orange | $ 3.99 | 008 | ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值