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

Sootah picture Sootah · Feb 13, 2011 · Viewed 114.4k times · Source

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

Answer

Gabe picture Gabe · Feb 13, 2011

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

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