Java String Left left(final String string, final int length)

Here you can find the source of left(final String string, final int length)

Description

Returns leftmost characters of a string.

License

Apache License

Parameter

Parameter Description
string String to be tested, may be null.
length The maximum length of the string to return.

Return

The leftmost characters of a string. If the string was null, or shorter than the specified lenght, the original string will be returned.

Declaration

public static String left(final String string, final int length) 

Method Source Code

//package com.java2s;
/*/*www .j a  v a 2 s  . co  m*/
 *  Copyright 2011 Eric F. Savage, code@efsavage.com
 *
 *   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 {
    /**
     * Returns leftmost characters of a string.
     * 
     * @param string
     *            String to be tested, may be null.
     * @param length
     *            The maximum length of the string to return.
     * @return The leftmost characters of a string. If the string was null, or
     *         shorter than the specified lenght, the original string will be
     *         returned.
     */
    public static String left(final String string, final int length) {
        if (string == null || string.length() < length) {
            return string;
        }
        return string.substring(0, length);
    }
}

Related

  1. left(final String s, final int len)
  2. left(final String text, final String sep)
  3. left(Object src, int length, String defaultValue)
  4. left(String baseString, int pos)
  5. left(String s, int l)