[java] Cut Java String at a number of character

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 following Java String :

String str = "abcdefghijklmnopqrtuvwxyz";

I would like to cut the String at length = 8 :

Result must be:

String strOut = "abcdefgh..."

This question is related to java string

The answer is


StringUtils.abbreviate("abcdefg", 6);

This will give you the following result: abc...

Where 6 is the needed length, and "abcdefg" is the string that needs to be abbrevieted.


Jakarta Commons StringUtils.abbreviate(). If, for some reason you don't want to use a 3rd-party library, at least copy the source code.

One big benefit of this over the other answers to date is that it won't throw if you pass in a null.


You can use safe substring:

org.apache.commons.lang3.StringUtils.substring(str, 0, LENGTH);

String strOut = str.substring(0, 8) + "...";

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

Use substring and concatenate:

if(str.length() > 50)
    strOut = str.substring(0,7) + "...";

Something like this may be:

String str = "abcdefghijklmnopqrtuvwxyz";
if (str.length() > 8)
    str = str.substring(0, 8) + "...";

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.