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. StringAlignUtils
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 i.e. LEFT
, CENTER
, and RIGHT
.
StringAlignUtils
also needs a parameter maxChars
, which is the length of characters in a single line. It the number of characters in the given String are more than maxChars
, the String is splitted into two Strings.
package com.howtodoinjava.examples; 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; } }
2. Java String Left Align Example
public static void main(String[] args) { 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) ); }
Program output.
3. Java String Right Align Example
public static void main(String[] args) { 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.RIGHT); System.out.println( util.format(sampleText) ); }
Program output.
4. Java String Center Align Example
public static void main(String[] args) { 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.CENTER); System.out.println( util.format(sampleText) ); }
Program output.
Feel free to edit and customize StringAlignUtils
as per the needs.
Happy Learning !!
I was trying to understand this line,
but I couldn’t figure out why you did that. Then I realized that x – 1/2x = 1/2x so you can just replace it with toAdd / 2.
BTW, in Python, center align is three lines:
That may be true in most situations, but not all.
Dear Sir,
Please send to me Left and right and center alignment StringAlignUtils.Java File.
Did you consider using Java string format APIs. Left and right alignment can be done by using native Java routines.
Yup !! I checked them as well. I wrote this class to get more flexibility e.g. I can mention that after N chars, print text in next line; OR i can align center as well. Also, code is free to modified as per need which provides more freedom. It’s not alternative to native APIs, it’s rather complementing them.