digitalmars.D.learn - Justify text
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, ' '); }
Aug 09 2010
On 09.08.2010 23:59, simendsjo wrote:return justify(s, Alignment.Right, width, ' ');Forgot zfill: string zfill(string s, int width) { return justify(s, Alignment.Right, width, '0'); }
Aug 09 2010