Java String Truncate truncate(String original, int number)

Here you can find the source of truncate(String original, int number)

Description

Keeps the 'number' first characters, and might be useful to keep your user's privacy :
 truncate("Hernandez", 3)
will produce: "Her"

If number is bigger than the size of the String, the whole string is kept :
 truncate("Hernandez", 24)
will produce: "Hernandez"

If number==0, the function returns an empty string.

License

Apache License

Parameter

Parameter Description
original a parameter
number a parameter

Exception

Parameter Description
IllegalArgumentException if number<0 or original is null

Return

a new smaller String.

Declaration

public static String truncate(String original, int number) 

Method Source Code

//package com.java2s;
/*/*w  w  w.  j  ava 2 s  . c  o m*/
 * Copyright 2007-2011 Nicolas Zozol
 *
 * 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 {
    /**
     * <p>Keeps the 'number' first characters, and might be useful to keep your user's privacy :<br/>
     * &nbsp;<code>truncate("Hernandez", 3)</code><br/>
     * will produce: "Her"
     *</p>
     * <p>
     * If number is bigger than the size of the String, the whole string is kept : <br/>
     * &nbsp;<code>truncate("Hernandez", 24)</code><br/>
     * will produce: "Hernandez"
     *</p>
     * <p>If number==0, the function returns an empty string.</p>
     * @param original
     * @param number
     * @return a new smaller String.
     * @throws IllegalArgumentException if number<0 or original is null
     */
    public static String truncate(String original, int number) {
        if (number < 0) {
            throw new IllegalArgumentException("number :" + number + " is <0");
        }
        if (original == null) {
            throw new IllegalArgumentException("original string is null");
        }
        String newLastName = original.length() >= number ? original.substring(0, number) : original;
        return newLastName;

    }
}

Related

  1. truncate(String input, int maxLength)
  2. truncate(String input, int size)
  3. truncate(String message)
  4. truncate(String message, int length, boolean includeCount)
  5. truncate(String message, String substring)
  6. truncate(String original, String ellipsis, int maxLength)
  7. truncate(String originalString, int size)
  8. truncate(String s)
  9. truncate(String s)