Java examples for java.lang:String Truncate
truncate a string by length and add Ellipses
//package com.java2s; public class Main { public static void main(String[] argv) { String src = "java2s.com"; int maxChars = 4; boolean addEllipses = true; System.out.println(truncate(src, maxChars, addEllipses)); }//from www. j a v a2 s.c om public static String truncate(String src, int maxChars, boolean addEllipses) { if (src != null) { if (src.length() > maxChars) { StringBuilder result = new StringBuilder(src.substring(0, maxChars)); if (addEllipses && maxChars < src.length()) { result.append("..."); } return result.toString(); } } return src; } public static int length(String source) { int result = 0; if (isNotEmpty(source)) { result = source.length(); } return result; } public static String substring(String source, int offset, int dataLength) { StringBuilder sb = new StringBuilder(); if (!isEmpty(source) && source.length() >= offset + dataLength) { sb.append(source.substring(offset, offset + dataLength)); } return sb.toString(); } public static boolean isNotEmpty(String str) { return !isEmpty(str); } public static boolean isEmpty(String str) { return (str == null || str.length() == 0); } }