C# - 在字符串中插入可变数量的空格? (格式化输出文件)

发布于 2024-10-16 22:47:53 字数 575 浏览 1 评论 0原文

我正在从填充 DataGridView 的列表中获取数据并将其导出到文本文件。我已经完成了将其导出到 CSV 的功能,并且还想做一个纯文本版本。

由于标题和其他元素的长度是可变的,因此当保存文件然后在记事本中打开文件时,它看起来很混乱,因为没有任何内容排列。

我希望输出看起来像这样:

Sample Title One   Element One   Whatever Else
Sample Title 2     Element 2     Whatever Else
S. T. 3            E3            Whatever Else

我想我可以循环遍历每个元素,以获得最长元素的长度,这样我就可以计算要向每个剩余元素添加多少个空格。

我的主要问题是:有没有一种优雅的方法可以将可变数量的字符添加到字符串中?如果有这样的东西就好了:myString.insert(index, charToInsert, howManyToInsert );

当然,我显然可以编写一个函数来通过循环来执行此操作,但我想看看是否有更好的方法。

I'm taking data from a list that I populate a DataGridView with and am exporting it to a text file. I've already done the function to export it to a CSV, and would like to do a plain text version as well.

Because the Titles and other elements are variable in length, when the file is saved and then opened in Notepad it looks like a mess because nothing lines up.

I'd like to have the output look like this:

Sample Title One   Element One   Whatever Else
Sample Title 2     Element 2     Whatever Else
S. T. 3            E3            Whatever Else

I figure that I can loop through each of the elements in order to get the length of the longest one so I can calculate how many spaces to add to each of the remaining element.

My main question is: Is there an elegant way to add a variable number of chars into a string? It'd be nice to have something like: myString.insert(index, charToInsert, howManyToInsert);

Of course, I can obviously just write a function to do this via a loop, but I wanted to see if there was a better way of doing it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

〃安静 2024-10-23 22:47:53

为此,您可能需要 myString.PadRight(totalLength, charToInsert)

有关详细信息,请参阅String.PadRight 方法 (Int32)

For this you probably want myString.PadRight(totalLength, charToInsert).

See String.PadRight Method (Int32) for more info.

美胚控场 2024-10-23 22:47:53

使用 String.Format()TextWriter.Format()(取决于您实际写入文件的方式)并指定字段的宽度。

String.Format("{0,20}{1,15}{2,15}", "Sample Title One", "Element One", "Whatever Else");

您还可以指定内插字符串中字段的宽度:

$"{"Sample Title One",20}{"Element One",15}{"Whatever Else",15}"

正如您所知,您可以使用适当的字符串构造函数创建重复字符的字符串。

new String(' ', 20); // string of 20 spaces

Use String.Format() or TextWriter.Format() (depending on how you actually write to the file) and specify the width of a field.

String.Format("{0,20}{1,15}{2,15}", "Sample Title One", "Element One", "Whatever Else");

You can specify the width of a field within interpolated strings as well:

$"{"Sample Title One",20}{"Element One",15}{"Whatever Else",15}"

And just so you know, you can create a string of repeated characters using the appropriate string contructor.

new String(' ', 20); // string of 20 spaces
心奴独伤 2024-10-23 22:47:53

使用String.Format

string title1 = "Sample Title One";
string element1 = "Element One";
string format = "{0,-20} {1,-10}";

string result = string.Format(format, title1, element1);
//or you can print to Console directly with
//Console.WriteLine(format, title1, element1);

格式为{0,-20}表示第一个参数的长度固定为20,负号保证字符串从左到右打印正确的。

Use String.Format:

string title1 = "Sample Title One";
string element1 = "Element One";
string format = "{0,-20} {1,-10}";

string result = string.Format(format, title1, element1);
//or you can print to Console directly with
//Console.WriteLine(format, title1, element1);

In the format {0,-20} means the first argument has a fixed length 20, and the negative sign guarantees the string is printed from left to right.

可可 2024-10-23 22:47:53

只是为了好玩,这是我在拥有 .PadRight 位之前编写的函数:

    public string insertSpacesAtEnd(string input, int longest)
    {
        string output = input;
        string spaces = "";
        int inputLength = input.Length;
        int numToInsert = longest - inputLength;

        for (int i = 0; i < numToInsert; i++)
        {
            spaces += " ";
        }

        output += spaces;

        return output;
    }

    public int findLongest(List<Results> theList)
    {
        int longest = 0;

        for (int i = 0; i < theList.Count; i++)
        {
            if (longest < theList[i].title.Length)
                longest = theList[i].title.Length;
        }
        return longest;
    }

    ////Usage////
    for (int i = 0; i < storageList.Count; i++)
    {
        output += insertSpacesAtEnd(storageList[i].title, longest + 5) +   storageList[i].rank.Trim() + "     " + storageList[i].term.Trim() + "         " + storageList[i].name + "\r\n";
    }

Just for kicks, here's the functions I wrote to do it before I had the .PadRight bit:

    public string insertSpacesAtEnd(string input, int longest)
    {
        string output = input;
        string spaces = "";
        int inputLength = input.Length;
        int numToInsert = longest - inputLength;

        for (int i = 0; i < numToInsert; i++)
        {
            spaces += " ";
        }

        output += spaces;

        return output;
    }

    public int findLongest(List<Results> theList)
    {
        int longest = 0;

        for (int i = 0; i < theList.Count; i++)
        {
            if (longest < theList[i].title.Length)
                longest = theList[i].title.Length;
        }
        return longest;
    }

    ////Usage////
    for (int i = 0; i < storageList.Count; i++)
    {
        output += insertSpacesAtEnd(storageList[i].title, longest + 5) +   storageList[i].rank.Trim() + "     " + storageList[i].term.Trim() + "         " + storageList[i].name + "\r\n";
    }
○闲身 2024-10-23 22:47:53

我同意 Justin 的观点,并且可以使用此处的 ASCII 代码引用 WhiteSpace CHAR< /强>
字符号 32 代表空格,因此:

string.Empty.PadRight(totalLength, (char)32);

另一种方法:
在自定义方法中手动创建所有空格并调用它:

private static string GetSpaces(int totalLength)
    {
        string result = string.Empty;
        for (int i = 0; i < totalLength; i++)
        {
            result += " ";
        }
        return result;
    }

并在代码中调用它以创建空格:
获取空间(14);

I agree with Justin, and the WhiteSpace CHAR can be referenced using ASCII codes here
Character number 32 represents a white space, Therefore:

string.Empty.PadRight(totalLength, (char)32);

An alternative approach:
Create all spaces manually within a custom method and call it:

private static string GetSpaces(int totalLength)
    {
        string result = string.Empty;
        for (int i = 0; i < totalLength; i++)
        {
            result += " ";
        }
        return result;
    }

And call it in your code to create white spaces:
GetSpaces(14);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文