Here you can find the source of truncate(String original, int number)
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.
Parameter | Description |
---|---|
original | a parameter |
number | a parameter |
Parameter | Description |
---|---|
IllegalArgumentException | if number<0 or original is null |
public static String truncate(String original, int number)
//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/> * <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/> * <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; } }