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
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