Limit the length of a string to a certain number of characters. - Java java.lang

Java examples for java.lang:String Truncate

Description

Limit the length of a string to a certain number of characters.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String string = "java2s.com";
        int length = 42;
        System.out.println(maxLength(string, length));
    }/*from  www  .ja  va  2  s  .co  m*/

    /**
     * Limit the length of a string to a certain number of characters. If the string is
     * truncated, a "..." is appended to the resulting string.
     *
     * @param string
     * @param length
     * @return The input string, limited to 'length' number of characters. String will end in '...' if it was truncated.
     */
    public static String maxLength(String string, int length) {

        //TODO: Fix less than four length issue

        if (string.length() <= length || length < 4) {
            return string;
        }

        int chopIndex = length - 3;

        // If chop falls on a natural word boundary, where done!
        char c = string.charAt(chopIndex);
        if (c < 'A' || c > 'z' || (c > 'Z' && c < 'a')) {
            return string.substring(0, chopIndex).trim() + "...";
        }

        // If chop falls in the middle of a word, lets try and avoid
        // that. Go back up to 8 alphanumeric characters.
        int chopAt = chopIndex;
        for (int i = chopIndex; i > 0 && i > chopIndex - 8; i--) {
            c = string.charAt(i);
            if (c < 'A' || c > 'z' || (c > 'Z' && c < 'a')) {
                chopAt = i;
                break;
            }
        }

        //TODO: handle when chomping falls on number boundary

        return string.substring(0, chopAt).trim() + "...";
    }
}

Related Tutorials