Here you can find the source of truncate(final String s, final int n)
Parameter | Description |
---|---|
s | the String to truncate |
n | the desired number of characters |
public static final String truncate(final String s, final int n)
//package com.java2s; /**//from ww w.j a v a 2 s . co m * The contents of this file are subject to the Regenstrief Public License * Version 1.0 (the "License"); you may not use this file except in compliance with the License. * Please contact Regenstrief Institute if you would like to obtain a copy of the license. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) Regenstrief Institute. All Rights Reserved. */ public class Main { /** * Retrieves the first n characters of s, or all of s if its length is less than n * * @param s the String to truncate * @param n the desired number of characters * @return the truncated String **/ public static final String truncate(final String s, final int n) { return length(s) <= n ? s : s.substring(0, n); } /** * Returns the length of the given array * * @param array the array for which to return the length * @return the length **/ public final static int length(final Object array) { if (array == null) { return 0; } else if (array instanceof byte[]) { return ((byte[]) array).length; } else if (array instanceof short[]) { return ((short[]) array).length; } else if (array instanceof int[]) { return ((int[]) array).length; } else if (array instanceof long[]) { return ((long[]) array).length; } else if (array instanceof float[]) { return ((float[]) array).length; } else if (array instanceof double[]) { return ((double[]) array).length; } else if (array instanceof boolean[]) { return ((boolean[]) array).length; } else if (array instanceof char[]) { return ((char[]) array).length; } return ((Object[]) array).length; } /** * Returns the length of the given array * * @param array the array for which to return the length * @return the length **/ public final static int length(final Object[] array) { return array == null ? 0 : array.length; } /** * Returns the length of the given array * * @param array the array for which to return the length * @return the length **/ public final static int length(final byte[] array) { return array == null ? 0 : array.length; } /** * Returns the length of the given array * * @param array the array for which to return the length * @return the length **/ public final static int length(final int[] array) { return array == null ? 0 : array.length; } /** * Retrieves the length of the CharSequence * * @param s the CharSequence * @return the length **/ public final static int length(final CharSequence s) { return s == null ? 0 : s.length(); } }