C# - Insert a variable number of spaces into a string? (Formatting an output file)
C#.NetVisual Studio-2010StringString FormattingC# Problem Overview
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
C# Solutions
Solution 1 - C#
For this you probably want myString.PadRight(totalLength, charToInsert)
.
See String.PadRight Method (Int32) for more info.
Solution 2 - C#
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 - C#
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 - C#
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 - C#
I agree with Justin, and the WhiteSpace CHAR can be referenced using [ASCII codes here][1] [1]: https://www.dotnetperls.com/ascii-table
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);