Java String Abbreviate abbreviate(String str, int maxWidth)

Here you can find the source of abbreviate(String str, int maxWidth)

Description

abbreviate

License

Apache License

Declaration

public static String abbreviate(String str, int maxWidth) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    public static String abbreviate(String str, int maxWidth) {
        return abbreviate(str, 0, maxWidth);
    }/*ww  w. j av a2 s  . c  om*/

    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));
    }

    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 "";
        }
        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 "";
        }
        if (start < 0) {
            start = 0;
        }
        if (end < 0) {
            end = 0;
        }
        return str.substring(start, end);
    }
}

Related

  1. abbreviate(String s, int maxLength)
  2. abbreviate(String src, int maxlen, String replacement)
  3. abbreviate(String str)
  4. abbreviate(String str, int maximumChars)
  5. abbreviate(String str, int maxlen, String appendIfLimit)
  6. abbreviate(String str, int maxWidth)
  7. abbreviate(String str, int maxWidth)
  8. abbreviate(String str, int maxWidth)
  9. abbreviate(String str, int maxWidth)