I need a procedure that "centers" a string inside a string that is consecutive characters of a fixed length. For instance,
======================== Instructions ============================
or
**************************** hehe ********************************
might be printed by calling
PrintBetweenChars("Instructions",'=');
or
PrintBetweenChars("hehe",'*');
respectively. Per my rules, the output will always have atleast one leading character and space and one trailing character and space, and the input
will be shrunk if need be. So if input
is abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
and the maximum line length is only 26
and the character is '-'
then the ouput is
- abcdefghijklmnopqrstuv -
Furthermore, to handle the case of input having an odd length like 5
, there will be one more character on the left than right. So the output would be like
-- abcdefghijklmnopqrstu -
if the input was abcdefghijklmnopqrstu
and the maximum line length was 26
. I tried implementing this and came up with the messiest-looking procedure ever:
public static void PrintBetweenChars ( string input, char c )
{
// Require input be at most (_outputMaxLength - 4) chars to accomodate 1 beginning and trailing char and space
// Shrink input if necessary
int shrunkInputLen = OutputFormatter._outputMaxLength - 4;
if ( input.Length > (shrunkInputLen) )
{
input.Remove(shrunkInputLen);
}
string charline = new String(c, (OutputFormatter._outputMaxLength - input.Length - 2) / 2);
Console.WriteLine("{0} {1} {2}", (input.Length & 1) == 1 ? charline + c.ToString() : charline, input, charline);
}
Is there a more compact, elegant, efficient, clever and readable way of doing this using the .NET library?
OutputFormatter
defined anywhere...am I missing something? Where else are you getting max length? \$\endgroup\$