Checks whether the inputString is longer than a specified length if so returns the truncated name appended by ellipsis, otherwise returns the original input. - Java java.lang

Java examples for java.lang:String Truncate

Description

Checks whether the inputString is longer than a specified length if so returns the truncated name appended by ellipsis, otherwise returns the original input.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String inputString = "java2s.com";
        int truncateLength = 2;
        System.out.println(truncate(inputString, truncateLength));
    }/*  w  w  w. ja v a2 s . c o  m*/

    /**
     * Checks whether the {@code inputString} is longer than a specified length
     * if so returns the truncated name appended by ellipsis,
     * otherwise returns the original input. <br>
     * E.g., "12345678" truncated to length 6 returns "123..."
     */
    public static String truncate(String inputString, int truncateLength) {
        if (!(inputString.length() > truncateLength)) {
            return inputString;
        }
        String result = inputString;
        if (inputString.length() > truncateLength) {
            result = inputString.substring(0, truncateLength - 3) + "...";
        }
        return result;
    }
}

Related Tutorials