Abbreviate a String using ellipses in both sides in Java

Description

The following code shows how to abbreviate a String using ellipses in both sides.

Example


// w  w w. ja v a 2s. c  o m
public class Main {
  public static void main(String[] argv) {
    System.out.println(abbreviate("this is a test from java2s.com", 13));
    System.out.println(abbreviate("this is a test from java2s.com", 13, 4));
  }

  public static String abbreviate(String str, int maxWidth) {
    return abbreviate(str, 0, maxWidth);
  }

  public static String abbreviate(String str, int offset, int maxWidth) {
    if (str == null) {
      return null;
    }
    if (maxWidth < 4) {
      throw new IllegalArgumentException(
          "Minimum abbreviation width is 4");
    }
    if (str.length() <= maxWidth) {
      return str;
    }
    if (offset > str.length()) {
      offset = str.length();
    }
    if ((str.length() - offset) < (maxWidth - 3)) {
      offset = str.length() - (maxWidth - 3);
    }
    if (offset <= 4) {
      return str.substring(0, maxWidth - 3) + "...";
    }
    if (maxWidth < 7) {
      throw new IllegalArgumentException(
          "Minimum abbreviation width with offset is 7");
    }
    if ((offset + (maxWidth - 3)) < str.length()) {
      return "..." + abbreviate(str.substring(offset), maxWidth - 3);
    }
    return "..." + str.substring(str.length() - (maxWidth - 3));
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Java Data Type »




Java Boolean
Java Byte
Java Character
Java Currency
Java Double
Java Enum
Java Float
Java Integer
Java Long
Java Short
Java Auto Grow Array
Java Array Compare
Java Array Convert
Java Array Copy Clone
Java Array Fill
Java Array Search and Sort
Java String Convert
Java String File
Java String Format
Java String Operation
Java BigDecimal
Java BigInteger