Java String Sub String substring(String source, int beginIndex, int endIndex)

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

Description

Returns a string that is a substring of this string.

License

Apache License

Parameter

Parameter Description
beginIndex the beginning index, inclusive.
endIndex the ending index, exclusive.

Return

the specified substring.

Declaration

public static String substring(String source, int beginIndex, int endIndex) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**/*from w w w  .  j  a  va  2s . co m*/
     * Returns a string that is a substring of this string. The substring begins
     * at the specified {@code beginIndex} and extends to the character at index
     * {@code endIndex - 1}. Thus the length of the substring is
     * {@code endIndex-beginIndex}.
     * <p>
     * 
     * </blockquote>
     * 
     * @from MAC This sample code comes from the MAC java virtual machine, since
     *       String.substring(int,int) doesn't do the same thing on mac and on
     *       windows...
     * @param beginIndex
     *            the beginning index, inclusive.
     * @param endIndex
     *            the ending index, exclusive.
     * @return the specified substring.
     * @exception IndexOutOfBoundsException
     *                if the {@code beginIndex} is negative, or {@code endIndex}
     *                is larger than the length of this {@code String} object,
     *                or {@code beginIndex} is larger than {@code endIndex}.
     */
    public static String substring(String source, int beginIndex, int endIndex) {
        if (beginIndex < 0)
            throw new StringIndexOutOfBoundsException(beginIndex);
        if (endIndex > source.length())
            throw new StringIndexOutOfBoundsException(endIndex);
        int subLen = endIndex - beginIndex;
        if (subLen < 0)
            throw new StringIndexOutOfBoundsException(subLen);
        String toreturn = "";
        for (int i = beginIndex; i < endIndex; ++i)
            toreturn += source.charAt(i);
        return toreturn;
    }
}

Related

  1. substring(String s, int start)
  2. substring(String s, int start, int length)
  3. substring(String s, int start, int stop)
  4. subString(String s, int startIndex, int count)
  5. substring(String self, Integer startIndex, Integer endIndex)
  6. substring(String source, int length, String padding)
  7. substring(String source, int offset, int dataLength)
  8. substring(String source, int size)
  9. substring(String source, int startIndex)