Java String Truncate truncate(final String originalString, final int maxChars)

Here you can find the source of truncate(final String originalString, final int maxChars)

Description

Truncates a string to a given length if it exceeds the length.

License

GNU General Public License

Parameter

Parameter Description
originalString The string to be truncated. A null value is returned unchanged..
maxChars The number of characters to keep. Input strings shorter than this length are returned unchanged. Values lower than <code>1</code> result in an empty string.

Return

The string truncated to the given length.

Declaration

public static String truncate(final String originalString, final int maxChars) 

Method Source Code

//package com.java2s;
/*//w w  w. j a va  2  s. c  o m
 * Copyright 2015 (C)  Christian Garbs <mitch@cgarbs.de>
 * Licensed under GNU GPL 3 (or later)
 */

public class Main {
    /**
     * Truncates a string to a given length if it exceeds the length.
     *
     * @param originalString The string to be truncated.  A null value is returned unchanged..
     * @param maxChars The number of characters to keep.  Input strings shorter than this
     *                 length are returned unchanged.  Values lower than <code>1</code> result
     *                 in an empty string.
     * @return The string truncated to the given length.
     */
    public static String truncate(final String originalString, final int maxChars) {
        if (originalString == null) {
            return null;
        }

        if (maxChars < 1) {
            return "";
        }

        if (maxChars >= originalString.length()) {
            return originalString;
        }

        return originalString.substring(0, maxChars);
    }
}

Related

  1. trunc(String string, int length)
  2. trunc(String txt, int size)
  3. trunc(String value, int len)
  4. truncate(final String description)
  5. truncate(final String in, final int maxLen)
  6. truncate(final String s, final int n)
  7. truncate(final String str, final int len)
  8. truncate(final String str, final int len)
  9. truncate(final String str, final int maxWidth)