Cut Java String at a number of character

后端 未结 8 1551
我寻月下人不归
我寻月下人不归 2020-12-18 18:43

I would like to cut a Java String when this String length is > 50, and add \"...\" at the end of the string.

Example :

I have the f

8条回答
  •  生来不讨喜
    2020-12-18 18:53

    You can use String#substring()

    if(str != null && str.length() > 8) {
        return str.substring(0, 8) + "...";
    } else {
        return str;
    }
    

    You could however make a function where you pass the maximum number of characters that can be displayed. The ellipsis would then cut in only if the width specified isn't enough for the string.

    public String getShortString(String input, int width) {
      if(str != null && str.length() > width) {
          return str.substring(0, width - 3) + "...";
      } else {
          return str;
      }
    }
    
    // abcdefgh...
    System.out.println(getShortString("abcdefghijklmnopqrstuvwxyz", 11));
    
    // abcdefghijk
    System.out.println(getShortString("abcdefghijk", 11)); // no need to trim
    

提交回复
热议问题