Java String Shorten shortenString(String s, int requiredLength)

Here you can find the source of shortenString(String s, int requiredLength)

Description

Shortens string to be no more than number of symbols specified

License

Apache License

Parameter

Parameter Description
s String to shorten
requiredLength Length to shorten string to

Return

Shortened string

Declaration

public static String shortenString(String s, int requiredLength) 

Method Source Code

//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;
    }
}

Related

  1. shortenPrefix(String prefix)
  2. shortenRemoteRef(final String origin, final String ref)
  3. shortenString(String orig, int charsToRemove)
  4. shortenString(String orig, int maxLength)
  5. shortenString(String s, int maxLength)
  6. shortenString(String source, int minLength, int maxLength, String suffix)
  7. shortenString(String str, int i)
  8. shortenString(String string, int minimumLength, int lengthToShortenBy)
  9. shortenString(String string, int targetLength, int maxDeviation)