I'm having an issue figuring out how to add padding to the whole of a body of text. My code is below.
public static String Format(List<string> list, int leftMargin, int rightMargin)
{
// Create an empty string to put the list of words into
string listTurnedIntoAString = "";
// Define the type of punctuation that is acceptable for have a space after.
string punctuation = ".,?!";
// turn the list of strings into one string
foreach (string item in list)
{
// if we find a punctuation mark remove the space before it
if (item.IndexOfAny(punctuation.ToCharArray()) == 0 && listTurnedIntoAString != String.Empty)
{
// Remove the space before the punctuation mark
listTurnedIntoAString = listTurnedIntoAString.Remove(listTurnedIntoAString.Length - 1);
}
// Add the next word to the string.
listTurnedIntoAString += $"{item} ";
}
// Add padding the left side
var stringPaddedLeft = listTurnedIntoAString.PadLeft(leftMargin + listTurnedIntoAString.Length);
// Add padding to the right side
var stringPaddedBothSides = stringPaddedLeft.PadRight(rightMargin + stringPaddedLeft.Length);
// Return the formated string
return stringPaddedBothSides;
}
Each line has to be parsed individually.
public static String Format(List<string> list, int leftMargin, int rightMargin)
{
// Create an empty string to put the list of words into
string listTurnedIntoAString = "";
// Define the type of punctuation that is acceptable for have a space after.
string punctuation = ".,?!-;";
// turn the list of strings into one string
foreach (string item in list)
{
// if we find a punctuation mark remove the space before it
if (item.IndexOfAny(punctuation.ToCharArray()) == 0 && listTurnedIntoAString != String.Empty)
{
// Remove the space before the punctuation mark
listTurnedIntoAString = listTurnedIntoAString.Remove(listTurnedIntoAString.Length - 1);
}
// Add the next word to the string.
listTurnedIntoAString += $"{item} ";
}
// Number of charters between each margin
int betweenMarginSpacing = rightMargin - leftMargin;
// Placeholder for the a new formatted string
string formattedString = "";
while (listTurnedIntoAString != String.Empty)
{
// check if we are close to the end of the list
if (listTurnedIntoAString.Length > betweenMarginSpacing)
{
// format each line
formattedString += $"{listTurnedIntoAString.Substring(0, betweenMarginSpacing).PadLeft(leftMargin + betweenMarginSpacing)}\n";
// remove the text from the unformatted string after it has been added to the formatted string.
listTurnedIntoAString = listTurnedIntoAString.Substring(betweenMarginSpacing);
}
else // we are at the end of the string
{
// append the rest of the string to the formatted string.
formattedString += listTurnedIntoAString.PadLeft(leftMargin + listTurnedIntoAString.Length);
// declare the formatted string empty
listTurnedIntoAString = String.Empty;
}
}
// Return the formated string
return formattedString;
}