Java String Sub String subString(String string, int beginIndex, int length)

Here you can find the source of subString(String string, int beginIndex, int length)

Description

Gets the sub string of the given string.

License

Open Source License

Parameter

Parameter Description
string the string.
beginIndex the zero-based begin index.
length the length of the sub string starting at the begin index.

Return

the sub string of the given string.

Declaration

public static String subString(String string, int beginIndex, int length) 

Method Source Code

//package com.java2s;

public class Main {
    public static final String EMPTY = "";

    /**/*from  w ww .j  a v  a  2s . co  m*/
     * Gets the sub string of the given string. If the beginIndex is larger than
     * the length of the string, the empty string is returned. If the beginIndex +
     * the length is larger than the length of the string, the part of the string
     * following the beginIndex is returned. Method is out-of-range safe.
     * 
     * @param string the string.
     * @param beginIndex the zero-based begin index.
     * @param length the length of the sub string starting at the begin index.
     * @return the sub string of the given string.
     */
    public static String subString(String string, int beginIndex, int length) {
        final int endIndex = beginIndex + length;

        if (beginIndex >= string.length()) {
            return EMPTY;
        }

        if (endIndex > string.length()) {
            return string.substring(beginIndex, string.length());
        }

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

Related

  1. substring(String str, int start, int end)
  2. subString(String str, int start, int end)
  3. substring(String str, int toCount)
  4. substring(String str, int toCount, String more)
  5. substring(String str, String delim)
  6. subString(String string, int index)
  7. substring(String string, int init, int end)
  8. substring(String string, int maxChars, String suffix)
  9. substring(String string, int start, int length)