Friday, May 1, 2009

Truncating a sentence

Here is something that we often ask ourselves how do we truncate a sentence and then append it with a trailing "...". We see this in articles, newspapers, texts in television advertisements. I am suggesting a method that might be useful for front-end developers to truncate the sentences pulled out from the database.

public static String truncate(String text, int length) {
return (text.length() <= length) ? text : text.substring(0, length) + " ...";
}
Simple isn't it? The use of this static method allows you to set a maximum length of the sentence to be truncated and then append it with the trailing "...".
Update: The code is also available in Python in this entry

0 comments:

Post a Comment