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

Java examples for java.lang:String Substring

Description

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

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String str = "java2s.com";
        int beginIndex = 2;
        System.out.println(substring(str, beginIndex));
    }//from  ww  w  .java  2 s.  com

    /**
     * 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 Tutorials