Java String Truncate truncateString(String str, int length, String suffix)

Here you can find the source of truncateString(String str, int length, String suffix)

Description

Truncate a string by the given length, cutting words if necessary.

License

Open Source License

Parameter

Parameter Description
string the string
length the max length
suffix the suffix to add if the string is > length

Return

the new string < length

Declaration

public static String truncateString(String str, int length, String suffix) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**//w ww  .ja va  2  s  .co  m
     * Truncate a string by the given length, cutting words if necessary.
     * 
     * @param string
     *          the string
     * @param length
     *          the max length
     * @param suffix
     *          the suffix to add if the string is > length
     * @return the new string < length
     */
    public static String truncateString(String str, int length, String suffix) {
        if (str != null && length >= 0) {
            suffix = (suffix == null ? "" : suffix);
            if (str.length() > (length - suffix.length())) {
                int size = length - suffix.length();
                while (size < 0) {
                    size++;
                }
                str = str.substring(0, size) + suffix;
            }
        }
        return (str == null ? null : str);
    }
}

Related

  1. truncateString(String s)
  2. truncateString(String s, int numChars)
  3. truncateString(String source, int prefixLength, int totalLength)
  4. truncateString(String source, String suffix)
  5. truncateString(String str, int length)
  6. truncateString(String str, int maxlen)
  7. truncateString(String str, int size)
  8. truncateString(String str, int toLen)
  9. truncateString(String string, int maxLength)