Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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( )

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata