Java String Sub String substring(String str, int beginIndex)

Here you can find the source of substring(String str, int beginIndex)

Description

same as String.substring, except that this version handles the case robustly when the index is out of bounds.

License

Open Source License

Declaration

public static String substring(String str, int beginIndex) 

Method Source Code

//package com.java2s;
/*//from  w w  w.j a v  a2 s. c  o m
Copyright (c) 2008 Arno Haase.
All rights reserved. This program and the accompanying materials
are made available under the terms of the Eclipse Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/epl-v10.html
    
Contributors:
Arno Haase - initial API and implementation
 */

public class Main {
    /**
     * same as String.substring, except that this version handles the case
     * robustly when the index is out of bounds.
     */
    public static String substring(String str, int beginIndex) {
        if (str == null)
            return null;
        if (beginIndex < 0)
            return str;
        if (beginIndex >= str.length())
            return "";

        return str.substring(beginIndex);
    }

    /**
     * same as String.substring, except that this version handles the case
     * robustly when one or both of the indexes is out of bounds.
     */
    public static String substring(String str, int beginIndex, int endIndex) {
        if (str == null)
            return null;
        if (beginIndex > endIndex)
            return "";
        if (beginIndex < 0)
            beginIndex = 0;
        if (endIndex > str.length())
            endIndex = str.length();

        return str.substring(beginIndex, endIndex);
    }
}

Related

  1. substring(String src, String fromToken, String toToken)
  2. subString(String src, String start, String to)
  3. subString(String src, String start, String to)
  4. subString(String srcStr, int subLen)
  5. substring(String str, char pattern)
  6. subString(String str, int beginIndex, int endIndex)
  7. substring(String str, int beginIndex, int endIndex)
  8. substring(String str, int beginIndex, int endIndex)
  9. substring(String str, int beginIndex, int len)