C#格式化文本(右对齐)

5

我是一个初学者,正在学习 C#。我正在制作一个模拟购物清单收据程序来管理您的购物。我生成了 .txt 收据,但在正确对齐字符串时遇到了问题,以下是我的代码:

public static void GenerateNewReciept(Customer customer)
{
    List<ShoppingItems> customerPurchaedItems;
    try
    {
        sw = File.AppendText("receipt.txt");

        //Customer object
        Customer customers = customer;
        //List of all items in list
        List<ShoppingList> customerItems = customer.CustomerShoppingList;
        DateTime todayDandT = DateTime.Now;

        //Making reciept layout
        sw.WriteLine("Date Generated: " + todayDandT.ToString("g", CultureInfo.CreateSpecificCulture("en-us")));
        sw.WriteLine("Customer: " + customer.FName + " " + customer.SName1);

        for (int i = 0; i < customerItems.Count; i++)
        {
            customerPurchaedItems = customerItems[i].ShoppingItems;
            foreach (ShoppingItems item in customerPurchaedItems)
            {
                sw.WriteLine(String.Format("{0,0} {1,25:C2}", item.ItemName, item.Price));  
            }
        }

        sw.WriteLine("Total {0,25:C2}", customerItems[0].computeTotalCost());
        sw.Close();
    }
    catch (FileNotFoundException)
    {
        Console.WriteLine("FILE NOT FOUND!");
    }
}

sw.WriteLine(String.Format("{0,-20} {1,25:C2}", item.ItemName, item.Price)); sw.WriteLine(String.Format("{0,-20} {1,25:C2}", "Total", total)); - 在这里,我希望商品的价格可以右对齐,但是一些商品名称较长,当应用了25个空格时,它们会错位。总价也是同样的情况。


当空间不足时,你想做什么?既然你有边界,我猜你知道如何处理边缘情况。 - Mihai-Daniel Virna
我不明白,你能详细解释一下吗? - dijam
1
在你的答案中,基本上就是我想表达的意思。每当你为某个问题提供解决方案时,请考虑输入不符合预期的情况以及如何处理它们。 - Mihai-Daniel Virna
1个回答

5

实际上,使用内置格式化可以实现此操作:

using System;

namespace Demo
{
    static class Program
    {
        public static void Main()
        {
            printFormatted("Short", 12.34);
            printFormatted("Medium", 1.34);
            printFormatted("The Longest", 1234.34);
        }

        static void printFormatted(string description, double cost)
        {
            string result = format(description, cost);
            Console.WriteLine(">" + result + "<");
        }

        static string format(string description, double cost)
        {
            return string.Format("{0,15} {1,9:C2}", description, cost);
        }
    }
}

这将打印:

>          Short    £12.34<
>         Medium     £1.34<
>    The Longest £1,234.34<

我已经实现了这个解决方案,只是为了澄清一下,当我们写 {0,15} 时,这意味着我们将字符串右对齐到 15 个字符,我们有 {1,9:C2} 这意味着因为所有的描述都在第 15 个位置结束,所以我们添加了 9 个字符。我们是对齐的,因为我们知道描述结束的位置。 - dijam
@dijam 是的,没错:这里的“15”表示“将该字段右对齐并用空格填充至15个字符”,9也是同理。因此,描述始终占用15个字符,数字始终占用9个字符——除非数字或字符串无法适应那么多字符,在这种情况下,将使用更多字符。 - Matthew Watson
好发现!+1 给你,我的答案就这样发出去了。 :-) - Heinzi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接