How to truncate a string
Short answer
Take the start of the string with substring(), limiting the length with Math.min():
void main() {
String text = "Hello, World";
IO.println(text.substring(0, Math.min(text.length(), 5)));
}Output:
HelloWith an ellipsis
Add an ellipsis only if the string is actually longer than the limit:
String truncate(String text, int max) {
return text.length() <= max ? text : text.substring(0, max - 1) + "…";
}
void main() {
IO.println(truncate("A very long title", 10));
IO.println(truncate("Short", 10));
}Output:
A very lo…
ShortAt a word boundary
To avoid cutting a word in half, find the last space before the limit:
String truncateWords(String text, int max) {
if (text.length() <= max) {
return text;
}
int space = text.lastIndexOf(' ', max);
return (space > 0 ? text.substring(0, space) : text.substring(0, max)) + "…";
}
void main() {
IO.println(truncateWords("Learn Java step by step", 12));
}Output:
Learn Java…Common mistake
Calling substring(0, max) on a string shorter than the limit:
void main() {
String text = "Hi";
IO.println(text.substring(0, 5));
}Output:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: Range [0, 5) out of bounds for length 2Limit the end with Math.min(text.length(), max).
Functions used in this recipe
- String.substring() — Returns the part of a string between two indexes.
- String.length() — Returns the number of characters in a string.
- Math.min() — Returns the smaller of two numbers.