Cut a description to length
A listing card has room for a fixed number of characters, and a description cut mid-word looks broken.
- Text already within the limit is returned untouched.
- Otherwise take the first `limit` characters and append three dots.
- If that slice would land mid-word, fall back to the last space inside it — but a slice that already ends on a word boundary keeps its last word.
- With no space to fall back to, cut hard at the limit and still append the dots.
- A limit of zero or less gives an empty string.
TruncateWords(text: string, limit: int) → string
C# 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.
Where you start
public string TruncateWords(string text, int limit) {
}
Worked examples
| Call | Result |
|---|---|
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 C#
public string TruncateWords(string text, int limit) {
if (limit <= 0) return "";
if (text.Length <= limit) return text;
string cut = text.Substring(0, limit);
if (text[limit] != ' ') {
int sp = cut.LastIndexOf(' ');
if (sp > 0) cut = cut.Substring(0, sp);
}
return cut.TrimEnd() + "...";
}