Aligning Strings

From Erlang Community

(Difference between revisions)
Revision as of 20:21, 7 September 2006 (edit)
213.171.204.166 (Talk)

← Previous diff
Current revision (08:50, 4 December 2006) (edit) (undo)
Andreas (Talk | contribs)
m (Reverted edits by Kaiserpanda (Talk); changed back to last version by 213.171.204.166)
 
(One intermediate revision not shown.)

Current revision

[edit] Problem

You want to align a string, left, right, or center. You might use this when generating reports, for example.

[edit] Solution

The easiest solution is to use the string module, which solves the left and right padding issues.

1> io:fwrite("|~s|~s|~n", [ string:left("Title",20), string:right("Price",10) ]).
|Title               |     Price|
ok
2> io:fwrite("|~s|~n", [ string:centre("Fabulous", 25) ]).
|        Fabulous         |
ok

left and right both default to using '$ ' (the space character) as the padding character; you may override this by providing the character in the third argument. The left and right functions also truncate the string if it's longer than the specified field width, but centre generates an error in that case.

Erlang/OTP Projects
Personal tools