I wrote a text adventure game a while back and today I looked at it to see how I did the word wrapping (to use in a new project); I'm curious if I went about it the right way. I realize I could use an array instead of a list and remove 2 dependencies from the class but wanted some other feedback as I may have missed something obvious.
public static string GetBorderedText(string Input, int AbsoluteLength, bool splitLines = true, int Offset = -4)
{
string outputString = "";
if(Input.Length > AbsoluteLength + Offset && splitLines)
{
List<string> words = Input.Split(' ').ToList();
string lineConstruction = "";
foreach (string s in words)
{
if (lineConstruction.Length + s.Length + 1 >= AbsoluteLength + Offset)
{
outputString += "+ " + GetPaddedSubstring(lineConstruction, AbsoluteLength, Offset) + " +" + Environment.NewLine;
lineConstruction = "";
lineConstruction += s + " ";
}
else
{
lineConstruction += s + " ";
}
}
outputString += "+ " + GetPaddedSubstring(lineConstruction, AbsoluteLength, Offset) + " +";
return outputString;
}
else
{
outputString = "+ " + GetPaddedSubstring(Input, AbsoluteLength, Offset) + " +";
return outputString;
}
}
where GetPaddedSubstring
is used for getting a substring padded to a certain length.
public static string GetPaddedSubstring(string Input, int AbsoluteLength, int Offset)
{
int targetLength = AbsoluteLength + Offset;
string output = "";
if(Input.Length > targetLength)
{
return Input.Substring(0, targetLength);
}
else
{
output = Input.PadRight(targetLength);
return output;
}
}
Lastly, for some examples. GetBorderedText
can take in something like
"This room looks sturdy, but old. Lots of storage and containers. There is a door on the far side."
And return something like this.
+ This room looks sturdy, but old. Lots of storage and containers. There is a door +
+ on the far side. +
The +
on the side are just to create a nice border within the Console window. (Hence the -4 default on Offset)