C# - Insert a variable number of spaces into a string? (Formatting an output file)

127,694

Solution 1

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

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

Solution 2

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

Solution 3

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.

Solution 4

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";
    }

Solution 5

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

Share:
127,694
Sootah
Author by

Sootah

Updated on March 05, 2020

Comments

  • Sootah
    Sootah about 4 years

    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.

    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.

    Thanks in advance!

    -Sootah

  • Sootah
    Sootah about 13 years
    Beautiful! Just exactly what I was hoping for.
  • Raven
    Raven about 9 years
    Thanks for this great find, can't believe this has existed since 2.0 and i had no idea what so ever!
  • Auguste Van Nieuwenhuyzen
    Auguste Van Nieuwenhuyzen about 8 years
    Thanks for the string constructor info. I don't even know why that's there, but I used it! Cool! :)
  • MegaMark
    MegaMark over 7 years
    Indeed, I knew about padding... but my use case called for the constructor logic found here. thanks
  • Edward
    Edward over 7 years
    Using the string.Format (and maybe with a combination of your second line of code) is there a way to pass in a variable int for the actual padding number?
  • Jeff Mercado
    Jeff Mercado over 7 years
    @Edward, you can. Basically just build the format string with the appropriate width and use that format string with String.Format(). e.g., String.Format($"The value is: {{0,{width}}}", value)
  • Edward
    Edward over 7 years
    So I was part of the way there in my try, I needed the extra pair of brackets (not sure why it needs to be double bracketed) plus the use of the $ inside the String.Format method.
  • Jeff Mercado
    Jeff Mercado over 7 years
    @Edward, within an interpolated string, curly braces are used for the start and stop points of the formatted value. If you wanted a literal curly brace, it has to be doubled. This applies to both the interpolated string and the format string that you pass into String.Format().
  • Edward
    Edward over 7 years
    @JeffMercado A little confused. The brackets are for the formatted values, that much I understand. Why is the value within the variable obtained only with it in its own set of brackets? If there is only normally one set of brackets then why the comment about making them literal if they weren't originally?
  • Jeff Mercado
    Jeff Mercado over 7 years
    @Edward we're doing two separate formattings, first generating a format string to be passed into String.Format() and the actual call to that function. Suppose we had a variable width = 20 and wanted to use that value to generate the string "{0,20}", we could either write it out as "{0," + width + "}" or using string interpolation: $"{{0,{width}}}". We're not doing any additional formatting to width at this point, we just want to insert the value. Remember, within an interpolated string, you need to double the braces if you want them inserted literally. "{" == $"{{"
  • Edward
    Edward over 7 years
    ok so ${{ is similar then to $"c:\\dir\\file" == c:\dir\file And that is also similar to @"c:\dir\file"correct? Though I still had no previous understanding that "{0," + width + "}" equaled {0,{width}}
  • Jeff Mercado
    Jeff Mercado over 7 years
    @Edward: you got it.