Automatically ellipsize a string in Java

前端 未结 5 1951
深忆病人
深忆病人 2020-12-17 01:55

Is there a method in Java to automatically ellipsize a string? Just in Java, not other libraries.

Thanks.

5条回答
  •  隐瞒了意图╮
    2020-12-17 02:41

    This method will return the ellipsized String:

    String ellipsize(String input, int maxLength) {
        String ellip = "...";
        if (input == null || input.length() <= maxLength 
               || input.length() < ellip.length()) {
            return input;
        }
        return input.substring(0, maxLength - ellip.length()).concat(ellip);
    }
    

提交回复
热议问题