diff --git a/src/text.cpp b/src/text.cpp index ae41a15e8..de6d4efb9 100644 --- a/src/text.cpp +++ b/src/text.cpp @@ -655,6 +655,7 @@ int characters (const std::string& str) } //////////////////////////////////////////////////////////////////////////////// +// Truncates a long line, and include a two-character ellipsis. std::string cutOff (const std::string& str, std::string::size_type len) { if (str.length () > len) @@ -715,3 +716,15 @@ std::string format (double value, int width, int precision) } //////////////////////////////////////////////////////////////////////////////// +std::string leftJustify (const std::string& input, const int width) +{ + return input + std::string (width - input.length (), ' '); +} + +//////////////////////////////////////////////////////////////////////////////// +std::string rightJustify (const std::string& input, const int width) +{ + return std::string (width - input.length (), ' ') + input; +} + +//////////////////////////////////////////////////////////////////////////////// diff --git a/src/text.h b/src/text.h index fe6ceb526..20a287a88 100644 --- a/src/text.h +++ b/src/text.h @@ -66,6 +66,8 @@ std::string format (int); std::string formatHex (int); std::string format (float, int, int); std::string format (double, int, int); +std::string leftJustify (const std::string&, const int); +std::string rightJustify (const std::string&, const int); // UTF-8 aware. int characters (const std::string&); diff --git a/test/text.t.cpp b/test/text.t.cpp index 23d0e4490..e6e3c33c2 100644 --- a/test/text.t.cpp +++ b/test/text.t.cpp @@ -34,7 +34,7 @@ Context context; //////////////////////////////////////////////////////////////////////////////// int main (int argc, char** argv) { - UnitTest t (208); + UnitTest t (214); // void wrapText (std::vector & lines, const std::string& text, const int width) std::string text = "This is a test of the line wrapping code."; @@ -416,6 +416,16 @@ int main (int argc, char** argv) // std::string format (double, int, int); + // std::string leftJustify (const std::string&, const int); + t.is (leftJustify ("foo", 3), "foo", "leftJustify foo,3 -> 'foo'"); + t.is (leftJustify ("foo", 4), "foo ", "leftJustify foo,4 -> 'foo '"); + t.is (leftJustify ("foo", 5), "foo ", "leftJustify foo,5 -> 'foo '"); + + // std::string rightJustify (const std::string&, const int); + t.is (rightJustify ("foo", 3), "foo", "rightJustify foo,3 -> 'foo'"); + t.is (rightJustify ("foo", 4), " foo", "rightJustify foo,4 -> ' foo'"); + t.is (rightJustify ("foo", 5), " foo", "rightJustify foo,5 -> ' foo'"); + return 0; }