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

时间:2021-10-26 23:13:54

Alrighty, 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.

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

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);

我的主要问题是:是否有一种优雅的方法可以将可变数量的字符添加到字符串中?有类似的东西很好: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.

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

Thanks in advance!

提前致谢!

-Sootah

-Sootah

4 个解决方案

#1


88  

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

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

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

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

#2


37  

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

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

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

#3


3  

Use String.Format:

使用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.

格式{0,-20}表示第一个参数具有固定长度20,负号表示字符串从左到右打印。

#4


2  

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

只是为了踢,这里是我写的函数之前我有.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";
    }

#1


88  

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

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

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

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

#2


37  

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

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

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

#3


3  

Use String.Format:

使用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.

格式{0,-20}表示第一个参数具有固定长度20,负号表示字符串从左到右打印。

#4


2  

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

只是为了踢,这里是我写的函数之前我有.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";
    }