Here you can find the source of shortenString(String s, int requiredLength)
Parameter | Description |
---|---|
s | String to shorten |
requiredLength | Length to shorten string to |
public static String shortenString(String s, int requiredLength)
//package com.java2s; /*/* w w w .j a va 2 s.c om*/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class Main { /** * Shortens string to be no more than number of symbols specified * * @param s * String to shorten * @param requiredLength * Length to shorten string to * @return Shortened string */ public static String shortenString(String s, int requiredLength) { if (s != null && s.length() > requiredLength) { s = s.substring(0, requiredLength + 1); int space = s.lastIndexOf(" "); int lineFeed = s.lastIndexOf("\n"); int tab = s.lastIndexOf("\t"); if (space > 0 || lineFeed > 0 || tab > 0) { int cut = space > lineFeed ? (space > tab ? space : tab) : (lineFeed > tab ? lineFeed : tab); s = s.substring(0, cut); } s += "..."; } return s; } }