string.format的用法
String.Format 是一个用于格式化字符串的方法,它在多种编程语言中都有不同的实现。在下面的示例中,我将展示C# 中String.Format 的用法。
C# 中的 String.Format 用法:
using System;
class Program
{
static void Main()
{
// 基本用法
string formattedString1 = String.Format("Hello, {0}!", "World");
Console.WriteLine(formattedString1);
// 多个参数
string formattedString2 = String.Format("My name is {0} and I am {1} years old.", "John", 30);
Console.WriteLine(formattedString2);
writeline用什么替代// 使用格式说明符
string formattedString3 = String.Format("The value of Pi is approximately {0:F2}", Math.PI);
Console.WriteLine(formattedString3);
// 指定参数顺序
string formattedString4 = String.Format("{1} is older than {0}", "Alice", "Bob");
Console.WriteLine(formattedString4);
}
}
在这个例子中:
{0}, {1} 是占位符,分别代表后面参数列表中的第一个和第二个参数。
:F2 是格式说明符,表示输出浮点数,并保留两位小数。
参数的顺序是从 0 开始的。
这将输出:
Hello, World!
My name is John and I am 30 years old.
The value of Pi is approximately 3.14
Bob is older than Alice
String.Format 提供了很大的灵活性,可以通过不同的占位符和格式说明符来满足不同的字符串格式化需求。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论