Skip to content

Instantly share code, notes, and snippets.

@thaniaclair
Last active December 17, 2015 05:49
Show Gist options
  • Select an option

  • Save thaniaclair/5561205 to your computer and use it in GitHub Desktop.

Select an option

Save thaniaclair/5561205 to your computer and use it in GitHub Desktop.
Truncador de texto
public class TextUtils {
/**
* Trunca um texto de acordo com o total de caracteres repassado.
* @param text texto para truncar.
* @param length o tamanho máximo para truncar.
* @return um literal truncado.
*/
public static String truncate(String text, int length) {
if (text.length() <= length) return text;
String shortText = text.substring(0, length);
char lastChar = text.charAt(length - 1);
char nextChar = text.charAt(length);
if (lastChar == ' ' || nextChar == ' ') return shortText;
int lastIndex = shortText.lastIndexOf(" ");
return shortText.substring(0, lastIndex);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment