Java String Truncate truncate(final String str, final int maxWidth)

Here you can find the source of truncate(final String str, final int maxWidth)

Description

Method to truncate the string when max width is given

License

Open Source License

Parameter

Parameter Description
str a parameter
maxWidth a parameter

Declaration

public static String truncate(final String str, final int maxWidth) 

Method Source Code

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

public class Main {
    /**//from   w  ww  .ja v  a  2 s .co m
     * Method to truncate the string when max width is given
     * 
     * @param str
     * @param maxWidth
     * @return {@link String}
     */
    public static String truncate(final String str, final int maxWidth) {
        return truncate(str, 0, maxWidth);
    }

    /**
     * Method to truncate the string when max width 
     * and offset is given
     * 
     * @param str
     * @param offset
     * @param maxWidth
     * @return {@link String}
     */
    public static String truncate(final String str, final int offset, final int maxWidth) {
        /* Offset and max width can't be less then 0 */
        if (offset < 0) {
            throw new IllegalArgumentException("offset cannot be negative");
        }
        if (maxWidth < 0) {
            throw new IllegalArgumentException("maxWidth cannot be negative");
        }
        /* If string is null, return null */
        if (str == null) {
            return null;
        }
        /* If offset is greater then list length, return empty string */
        if (offset > str.length()) {
            return "";
        }
        /* If valid scenario, find where we have to stop */
        if (str.length() > maxWidth) {
            final int ix = offset + maxWidth > str.length() ? str.length() : offset + maxWidth;
            return str.substring(offset, ix);
        }
        return str.substring(offset);
    }

    public static String substring(final String str, int start) {
        return str;
    }
}

Related

  1. truncate(final String in, final int maxLen)
  2. truncate(final String originalString, final int maxChars)
  3. truncate(final String s, final int n)
  4. truncate(final String str, final int len)
  5. truncate(final String str, final int len)
  6. truncate(final String target, final int maxSize)
  7. truncate(final String value, final int width)
  8. truncate(Object truncateMe, int maxLength, String suffix)
  9. truncate(String eval, String suffix, int targetLength)