Menu
CoddyTech

字符串格式化

本课属于 Coddy C# 学习旅程的“基础知识”单元。第 63 课,共 69 课。

在 C# 中,String.Format() 是一种强大的方法,可用于创建格式化字符串。它可以让你以易读且可自定义的方式将文本与变量组合起来。此方法使用格式说明符来定义如何将变量插入字符串。

我们来学习如何在 C# 中使用字符串格式化:

String.Format() 的基本语法是:

string formattedString = String.Format("format_string", arg0, arg1, ...);

其中:

  • format_string:包含文本和格式说明符的字符串。
  • arg0, arg1, ...:要插入到 format_string 中的变量。

我们来看看格式说明符。花括号中的数字表示参数的位置:

  • {0}:表示第一个参数(arg0)
  • {1}:表示第二个参数(arg1)
  • {2}:表示第三个参数(arg2)
  • 依此类推……

我们来试试一个使用不同类型参数的简单示例:

string name = "Alice";
int age = 30;
double price = 19.99;

string formatted = String.Format("Name: {0}, Age: {1}, Price: {2}", name, age, price);
Console.WriteLine(formatted);

运行这段代码后,你会在屏幕上看到:Name: Alice, Age: 30, Price: 19.99

你还可以在冒号后添加格式说明符,进一步控制格式。格式说明符由一个字母组成(例如,F 表示定点小数),后面可以跟一个表示精度的数字:

// 将数字格式化为保留 2 位小数
double number = 123.4567;
string formatted = String.Format("The value is {0:F2}", number);
Console.WriteLine(formatted);

运行这段代码后,你会在屏幕上看到:The value is 123.46

你可以使用 F1、F2、F3 等来指定不同的小数位数。

challenge icon

挑战

简单

创建一个名为 CreateFormattedString 的方法,它接受以下参数:

  1. 一个字符串 productName。
  2. 一个整数 quantity。
  3. 一个双精度浮点数 unitPrice。

该方法应返回一个格式化字符串,按以下格式组合这些值:

Product: [productName], Quantity: [quantity], Unit Price: [unitPrice]

将 unitPrice 格式化为小数点后五位,将 quantity 格式化为小数点后一位(将其转换为 double),并将 productName 的首字符转换为大写。

例如,如果 productName 是 "laptop",quantity 是 3,且 unitPrice 是 1299.9999,该方法应返回:

Product: Laptop, Quantity: 3.0, Unit Price: 1299.99990

若要提取首字符,同时将其保留为 String 类型而不是 char 类型,请使用:str.Substring(0,1)

亲手试试

using System;

public class Program {
    public static string CreateFormattedString(string productName, int quantity, double unitPrice) {
        // 在这里编写你的代码
    }

    public static void Main(string[] args) {
        string product = Console.ReadLine();
        int qty = int.Parse(Console.ReadLine());
        double price = double.Parse(Console.ReadLine());
        string formattedString = CreateFormattedString(product, qty, price);
        Console.WriteLine(formattedString);
    }
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

基础知识中的所有课

自己练习: C# 在线编译器