Cut Java String at a number of character

后端 未结 8 1490
我寻月下人不归
我寻月下人不归 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:45

    You can use safe substring:

    org.apache.commons.lang3.StringUtils.substring(str, 0, LENGTH);
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-18 18:55
    String strOut = str.substring(0, 8) + "...";
    
    0 讨论(0)
  • Use substring

    String strOut = "abcdefghijklmnopqrtuvwxyz"
    String result = strOut.substring(0, 8) + "...";// count start in 0 and 8 is excluded
    System.out.pritnln(result);
    

    Note: substring(int first, int second) takes two parameters. The first is inclusive and the second is exclusive.

    0 讨论(0)
  • 2020-12-18 19:00

    Something like this may be:

    String str = "abcdefghijklmnopqrtuvwxyz";
    if (str.length() > 8)
        str = str.substring(0, 8) + "...";
    
    0 讨论(0)
  • 2020-12-18 19:08

    Use substring and concatenate:

    if(str.length() > 50)
        strOut = str.substring(0,7) + "...";
    
    0 讨论(0)
提交回复
热议问题