Drill

ProblemsJava › text

Cut a description to length

mediumtextStringsParsingJava

A listing card has room for a fixed number of characters, and a description cut mid-word looks broken.

truncateWords(text: string, limit: int) → string

Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

String truncateWords(String text, int limit) {
    
}

Worked examples

CallResult
truncateWords("The quick brown fox", 10)"The quick..."
truncateWords("Supercalifragilistic", 5)"Super..."
truncateWords("Short", 10)"Short"
truncateWords("a b c d e f", 5)"a b c..."

Hint

Look at the character sitting at `limit`: if it is a space, the slice is already clean and needs no trimming back.

Reference solution in Java
String truncateWords(String text, int limit) {
    if (limit <= 0) return "";
    if (text.length() <= limit) return text;
    String cut = text.substring(0, limit);
    if (text.charAt(limit) != ' ') {
        int sp = cut.lastIndexOf(' ');
        if (sp > 0) cut = cut.substring(0, sp);
    }
    int e = cut.length();
    while (e > 0 && Character.isWhitespace(cut.charAt(e - 1))) e--;
    return cut.substring(0, e) + "...";
}

The same problem in another language

More text problems in Java