abbreviate string by length - Java java.lang

Java examples for java.lang:String Truncate

Description

abbreviate string by length

Demo Code


//package com.java2s;

public class Main {
  public static void main(String[] argv) {
    String str = "this is a test test test test test test test test test test test java2s.com ";
    int maxWidth = 20;
    System.out.println(abbreviate(str, maxWidth));
  }/*from   w ww . j  av  a  2s  .  co m*/

  public static final String EMPTY_STRING = "";

  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) {
      maxWidth = 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) {
      maxWidth = 7;
    }

    if ((offset + (maxWidth - 3)) < str.length()) {
      return "..." + abbreviate(str.substring(offset), maxWidth - 3);
    }

    return "..." + str.substring(str.length() - (maxWidth - 3));
  }

  public static String substring(String str, int start) {
    if (str == null) {
      return null;
    }

    if (start < 0) {
      start = str.length() + start;
    }

    if (start < 0) {
      start = 0;
    }

    if (start > str.length()) {
      return EMPTY_STRING;
    }

    return str.substring(start);
  }

  public static String substring(String str, int start, int end) {
    if (str == null) {
      return null;
    }

    if (end < 0) {
      end = str.length() + end;
    }

    if (start < 0) {
      start = str.length() + start;
    }

    if (end > str.length()) {
      end = str.length();
    }

    if (start > end) {
      return EMPTY_STRING;
    }

    if (start < 0) {
      start = 0;
    }

    if (end < 0) {
      end = 0;
    }

    return str.substring(start, end);
  }
}

Related Tutorials