Left, Right, or Center Align a String in Java

Learn to align a string to left, right, or center. I have created a utility class StringAlignUtils, which wraps all the logic inside it and provides convenient methods that we can call directly.

1. Using Custom Formatting on Long Text

1.1. StringAlignUtils Class

The StringAlignUtils class extends java.text.Format class. Format is an abstract base class for formatting locale-sensitive information such as dates, messages, and numbers.

StringAlignUtils defines three enum constants for alignment orders.

  • LEFT
  • CENTER
  • RIGHT

The StringAlignUtils also needs a parameter maxChars specifying the length of characters in a single line. If the number of characters in the given String is more than maxChars, the String is split into two Strings.

import java.text.FieldPosition;
import java.text.Format;
import java.text.ParsePosition;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
 
public class StringAlignUtils extends Format {
 
  private static final long serialVersionUID = 1L;
 
  public enum Alignment {
    LEFT, CENTER, RIGHT,
  }
 
  /** Current justification for formatting */
  private Alignment currentAlignment;
 
  /** Current max length of a line */
  private int maxChars;
 
  public StringAlignUtils(int maxChars, Alignment align) {
    switch (align) {
      case LEFT:
      case CENTER:
      case RIGHT:
        this.currentAlignment = align;
        break;
      default:
        throw new IllegalArgumentException("invalid justification arg.");
    }
    if (maxChars < 0) {
      throw new IllegalArgumentException("maxChars must be positive.");
    }
    this.maxChars = maxChars;
  }
 
  public StringBuffer format(Object input, StringBuffer where, FieldPosition ignore)
  {
    String s = input.toString();
    List<String> strings = splitInputString(s);
    ListIterator<String> listItr = strings.listIterator();
     
    while (listItr.hasNext()) 
    {
      String wanted = listItr.next();
       
      //Get the spaces in the right place.
      switch (currentAlignment) 
      {
        case RIGHT:
          pad(where, maxChars - wanted.length());
          where.append(wanted);
          break;
 
        case CENTER:
          int toAdd = maxChars - wanted.length();
          pad(where, toAdd / 2);
          where.append(wanted);
          pad(where, toAdd - toAdd / 2);
          break;
 
        case LEFT:
          where.append(wanted);
          pad(where, maxChars - wanted.length());
          break;
        }
        where.append("\n");
    }
    return where;
  }
 
  protected final void pad(StringBuffer to, int howMany) {
    for (int i = 0; i < howMany; i++)
      to.append(' ');
  }
 
  String format(String s) {
    return format(s, new StringBuffer(), null).toString();
  }
 
  /** ParseObject is required, but not useful here. */
  public Object parseObject(String source, ParsePosition pos) {
    return source;
  }
 
  private List<String> splitInputString(String str) {
    List<String> list = new ArrayList<String>();
    if (str == null)
      return list;
    for (int i = 0; i < str.length(); i = i + maxChars) 
    {
      int endindex = Math.min(i + maxChars, str.length());
      list.add(str.substring(i, endindex));
    }
    return list;
  }
}

1.2. String Left Align Example

String sampleText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt "
    + "ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris "
    + "nisi ut aliquip ex ea commodo consequat.";

StringAlignUtils util = new StringAlignUtils(50, Alignment.LEFT);
System.out.println( util.format(sampleText) );
left-aligned-text-example-java

1.3. String Right Align Example

StringAlignUtils util = new StringAlignUtils(50, Alignment.RIGHT);
System.out.println( util.format(sampleText) );

Program output.

right-aligned-text-example-java

1.4. String Center Align Example

StringAlignUtils util = new StringAlignUtils(50, Alignment.CENTER);
System.out.println( util.format(sampleText) );

Program output.

center-aligned-text-example-java

Feel free to edit and customize StringAlignUtils as per the needs.

2. Conclusion

This short Java tutorial taught us to align long strings in Java. We learned to align left, right, and center using padded spaces with examples.

Happy Learning !!

Leave a Reply

4 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial