Java - Write code to truncate a string regardless of its length.

Requirements

Write code to truncate a string regardless of its length.

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String str = "book2s.com";
        int maxLen = 4;
        System.out.println(truncate(str, maxLen));
    }/* w w  w. jav  a 2 s  .c  o m*/

    /**
     * truncates a string regardless of its length. This method is a workaround
     * for a shortcoming of String.substring (int, int) that is unable to handle
     * the case where the number of characters would extend beyond the end of
     * the string.
     */
    public static String truncate(String str, int maxLen) {
        if (str == null || str.length() < maxLen)
            return str;
        if (maxLen < 0)
            return "";
        return str.substring(0, maxLen);
    }

    /**
     * same as String.substring, except that this version handles the case
     * robustly when the index is out of bounds.
     */
    public static String substring(String str, int beginIndex) {
        if (str == null)
            return null;
        if (beginIndex < 0)
            return str;
        if (beginIndex >= str.length())
            return "";

        return str.substring(beginIndex);
    }

    /**
     * same as String.substring, except that this version handles the case
     * robustly when one or both of the indexes is out of bounds.
     */
    public static String substring(String str, int beginIndex, int endIndex) {
        if (str == null)
            return null;
        if (beginIndex > endIndex)
            return "";
        if (beginIndex < 0)
            beginIndex = 0;
        if (endIndex > str.length())
            endIndex = str.length();

        return str.substring(beginIndex, endIndex);
    }
}