Justify text

simendsjo simen.endsjo at pandavre.com
Mon Aug 9 14:59:43 PDT 2010


Phobos assumes that you only want to fill with spaces when justifying 
text. I merged the functions with a user supplied character. Don't think 
it should be much slower.. Just the switch extra switch if the function 
is inlined.. (but don't take my word for it :) )?

enum Alignment { Right, Left, Center }

string justify(string text, Alignment alignment, int width, char symbol)
{
     if (text.length >= width)
         return text;

     char[] result = new char[width];
     switch(alignment)
     {
         case Alignment.Right:
             result[0 .. width - text.length] = symbol;
             result[width - text.length .. width] = text;
             break;
         case Alignment.Center:
             int left = (width - text.length) / 2;
             result[0 .. left] = symbol;
             result[left .. left + text.length] = text;
             result[left + text.length .. width] = symbol;
             break;
         case Alignment.Left:
             result[0 .. text.length] = text;
             result[text.length .. width] = symbol;
             break;
         default:
             assert(false);
     }

     return assumeUnique(result);
}

string ljustify(string s, int width)
{
     return justify(s, Alignment.Left, width, ' ');
}

string rjustify(string s, int width)
{
     return justify(s, Alignment.Right, width, ' ');
}

string center(string s, int width)
{
     return justify(s, Alignment.Center, width, ' ');
}


More information about the Digitalmars-d-learn mailing list