Here you can find the source of truncate(String str, int maxLen)
public static String truncate(String str, int maxLen)
//package com.java2s; /*// www.j a v a 2s . c o m Copyright (c) 2008 Arno Haase. All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/epl-v10.html Contributors: Arno Haase - initial API and implementation */ public class Main { /** * truncates a string regardless of its length. This method is a workaround * for a shortcoming of String.substring (int, int) that is unable to handle * the case where the number of characters would extend beyond the end of * the string. */ public static String truncate(String str, int maxLen) { if (str == null || str.length() < maxLen) return str; if (maxLen < 0) return ""; return str.substring(0, maxLen); } /** * same as String.substring, except that this version handles the case * robustly when the index is out of bounds. */ public static String substring(String str, int beginIndex) { if (str == null) return null; if (beginIndex < 0) return str; if (beginIndex >= str.length()) return ""; return str.substring(beginIndex); } /** * same as String.substring, except that this version handles the case * robustly when one or both of the indexes is out of bounds. */ public static String substring(String str, int beginIndex, int endIndex) { if (str == null) return null; if (beginIndex > endIndex) return ""; if (beginIndex < 0) beginIndex = 0; if (endIndex > str.length()) endIndex = str.length(); return str.substring(beginIndex, endIndex); } }