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 safe substring:
org.apache.commons.lang3.StringUtils.substring(str, 0, LENGTH);
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
String strOut = 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.
Something like this may be:
String str = "abcdefghijklmnopqrtuvwxyz";
if (str.length() > 8)
str = str.substring(0, 8) + "...";
Use substring and concatenate:
if(str.length() > 50)
strOut = str.substring(0,7) + "...";