Aligning Strings
Problem
You want to align strings left, right, or centered.
Solution
Do the math yourself, and use substring
(Section 3.2) and a StringBuffer
(Section 3.4). Or, just use my
StringAlign
class, which is based on the
java.text.Format
class.
Discussion
Centering, or left- or right-aligning text, comes up surprisingly
often. Suppose you want to print a simple report with centered page
numbers. There doesn’t seem to be anything in the standard API
that will do the job fully for you. But I have written a class called
StringAlign
that will. Here’s how you might
use it:
/* Align a page number on a 70-character line. */ public class StringAlignSimple { public static void main(String[] args) { // Construct a "formatter" to center strings. StringAlign formatter = new StringAlign(70, StringAlign.JUST_CENTER); // Try it out, for page "i" System.out.println(formatter.format("- i -")); // Try it out, for page 4. Since this formatter is // optimized for Strings, not specifically for page numbers, // we have to convert the number to a String System.out.println(formatter.format(Integer.toString(4))); } }
If we compile and run this class, it prints the two demonstration line numbers centered, as shown:
> jikes +E -d . StringAlignSimple.java > java StringAlignSimple - i - 4 >
Here is the code for the StringAlign
class. Note
that this class extends a class called
Format
. In the package
java.text
there is
a series of Format
classes; they all have at least
one method called format( )
Get Java Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.