Java String Shorten shorten(String text, int size, int mode)

Here you can find the source of shorten(String text, int size, int mode)

Description

Shortens a given String "text" down to size length, indicating the shortening by three dots ("...").

License

Open Source License

Parameter

Parameter Description
text The string to shorten
size The size the text is to shortened to.
mode The mode in which the string shall be shortened

Return

The shortened string.

Declaration

public static String shorten(String text, int size, int mode) 

Method Source Code

//package com.java2s;

public class Main {
    public static final int SHORTEN_START = 1;
    public static final int SHORTEN_MIDDLE = 2;
    public static final int SHORTEN_END = 3;
    private static final String SHORTEN_STRING = "...";

    /**/*ww  w .  ja  v  a  2s  .c o  m*/
     * Shortens a given String "text" down to size length, indicating the shortening by three dots ("..."). Mode
     * determines the position of the dots and where the text will be cut off.
     *
     * @param text The string to shorten
     * @param size The size the text is to shortened to.
     * @param mode The mode in which the string shall be shortened
     * @return The shortened string.
     */
    public static String shorten(String text, int size, int mode) {
        StringBuilder temp = null;
        size = Math.min(text.length(), size);
        switch (mode) {
        case SHORTEN_START: {
            int length = size - 3;
            temp = new StringBuilder(SHORTEN_STRING);
            temp.append(text.substring(text.length() - length));
            break;
        }
        case SHORTEN_MIDDLE: {
            int length = size >> 1;
            temp = new StringBuilder(text.substring(0, length - 3));
            temp.append(SHORTEN_STRING);
            temp.append(text.substring(text.length() - length));
            break;
        }
        case SHORTEN_END: {
            int length = size - 3;
            temp = new StringBuilder(text.substring(0, length));
            temp.append(SHORTEN_STRING);
            break;
        }
        }
        return temp.toString();
    }
}

Related

  1. shorten(String str, int length)
  2. shorten(String string, boolean isPrefix)
  3. shorten(String string, int size)
  4. shorten(String string, int upTo)
  5. shorten(String text, int max)
  6. shorten(String[] a, int from, int to)
  7. shortenAddress(String address)
  8. shortenArray(byte[] src, int length)
  9. shortenClassName(Class klass)