How do I abbreviate a String with ellipses?
Author: Deron Eriksson
Description: This Java example shows how to abbreviate a String with ellipses.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)

StringUtils in the Commons LangS library has two abbreviate() methods that can be used to abbreviate Strings with ellipses. The first method takes the String to abbreviate and the number of characters to display from the front of the String, including the ellipses. The second method takes 3 arguments and places ellipses at the front and back of the abbreviated section. The first argument is the String to abbreviate, the second argument is the starting index for the front ellipses, and the third argument is the ending indexs for the back ellipses.

The AbbreviateTest class demonstrates these two methods with four different Strings.

package test;

import org.apache.commons.lang.StringUtils;

public class AbbreviateTest {

	public static void main(String[] args) throws Exception {

		String str1 = "This is a string to abbreviate";

		String str2 = "Short string";

		String str3 = "A fairly short string";

		String str4 = "This string is quite a bit longer than the other strings";


	public static void abbreviate(String str) {
		System.out.printf("%-40s %s\n", "Original:", str);
		System.out.printf("%-40s %s\n", "StringUtils.abbreviate(str, 20)", StringUtils.abbreviate(str, 20));
		System.out.printf("%-40s %s\n\n", "StringUtils.abbreviate(str, 10, 20):", StringUtils.abbreviate(str, 10, 20));


The console output from AbbreviateTest is shown below.


Original:                                This is a string to abbreviate
StringUtils.abbreviate(str, 20)          This is a string ...
StringUtils.abbreviate(str, 10, 20):     ...string to abbr...

Original:                                Short string
StringUtils.abbreviate(str, 20)          Short string
StringUtils.abbreviate(str, 10, 20):     Short string

Original:                                A fairly short string
StringUtils.abbreviate(str, 20)          A fairly short st...
StringUtils.abbreviate(str, 10, 20):     A fairly short st...

Original:                                This string is quite a bit longer than the other strings
StringUtils.abbreviate(str, 20)          This string is qu...
StringUtils.abbreviate(str, 10, 20):     ...g is quite a b...