回顾JavaSE(7)-String(6)String API 获取功能

来源:互联网 发布:淘宝个人闲置在哪里 编辑:程序博客网 时间:2024/05/29 04:45

今天我们结合源代码和实例一起来学习一下String类的获取功能,主要包括这几个函数:length、charAt、indexOf、substring。


int length()

<span style="font-size:18px;">    /**     * Returns the length of this string.     * The length is equal to the number of <a href="Character.html#unicode">Unicode     * code units</a> in the string.     *     * @return  the length of the sequence of characters represented by this     *          object.     */    public int length() {        return count;    }</span>


String s19 = "HelloWorld";
System.out.println("s19.length():" + s19.length());

输出:s19.length():10


需要注意的是String的索引也是从0开始。

char charAt(int index)

<span style="font-size:18px;">    /**     * Returns the <code>char</code> value at the     * specified index. An index ranges from <code>0</code> to     * <code>length() - 1</code>. The first <code>char</code> value of the sequence     * is at index <code>0</code>, the next at index <code>1</code>,     * and so on, as for array indexing.     *     * <p>If the <code>char</code> value specified by the index is a     * <a href="Character.html#unicode">surrogate</a>, the surrogate     * value is returned.     *     * @param      index   the index of the <code>char</code> value.     * @return     the <code>char</code> value at the specified index of this string.     *             The first <code>char</code> value is at index <code>0</code>.     * @exception  IndexOutOfBoundsException  if the <code>index</code>     *             argument is negative or not less than the length of this     *             string.     */    public char charAt(int index) {        if ((index < 0) || (index >= count)) {            throw new StringIndexOutOfBoundsException(index);        }        return value[index + offset];    }</span>


System.out.println("s19.charAt(1):" + s19.charAt(1));

输出:s19.charAt(1):e

System.out.println("s19.charAt(-1):" + s19.charAt(-1));

输出:Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1


int indexOf(intch)

<span style="font-size:18px;">    /**     * Returns the index within this string of the first occurrence of     * the specified character. If a character with value     * <code>ch</code> occurs in the character sequence represented by     * this <code>String</code> object, then the index (in Unicode     * code units) of the first such occurrence is returned. For     * values of <code>ch</code> in the range from 0 to 0xFFFF     * (inclusive), this is the smallest value <i>k</i> such that:     * <blockquote><pre>     * this.charAt(<i>k</i>) == ch     * </pre></blockquote>     * is true. For other values of <code>ch</code>, it is the     * smallest value <i>k</i> such that:     * <blockquote><pre>     * this.codePointAt(<i>k</i>) == ch     * </pre></blockquote>     * is true. In either case, if no such character occurs in this     * string, then <code>-1</code> is returned.     *     * @param   ch   a character (Unicode code point).     * @return  the index of the first occurrence of the character in the     *          character sequence represented by this object, or     *          <code>-1</code> if the character does not occur.     */    public int indexOf(int ch) {return indexOf(ch, 0);    }</span>

System.out.println("s19.indexOf('l'):" + s19.indexOf('l'));

输出:s19.length():10


int indexOf(String str)

<span style="font-size:18px;">    /**     * Returns the index within this string of the first occurrence of the     * specified substring. The integer returned is the smallest value     * <i>k</i> such that:     * <blockquote><pre>     * this.startsWith(str, <i>k</i>)     * </pre></blockquote>     * is <code>true</code>.     *     * @param   str   any string.     * @return  if the string argument occurs as a substring within this     *          object, then the index of the first character of the first     *          such substring is returned; if it does not occur as a     *          substring, <code>-1</code> is returned.     */    public int indexOf(String str) {return indexOf(str, 0);    }</span>

System.out.println("s19.indexOf(\"ll\"):" + s19.indexOf("ll"));

输出:s19.indexOf("ll"):2


int indexOf(intch,int fromIndex)

<span style="font-size:18px;">    /**     * Returns the index within this string of the first occurrence of the     * specified character, starting the search at the specified index.     * <p>     * If a character with value <code>ch</code> occurs in the     * character sequence represented by this <code>String</code>     * object at an index no smaller than <code>fromIndex</code>, then     * the index of the first such occurrence is returned. For values     * of <code>ch</code> in the range from 0 to 0xFFFF (inclusive),     * this is the smallest value <i>k</i> such that:     * <blockquote><pre>     * (this.charAt(<i>k</i>) == ch) && (<i>k</i> >= fromIndex)     * </pre></blockquote>     * is true. For other values of <code>ch</code>, it is the     * smallest value <i>k</i> such that:     * <blockquote><pre>     * (this.codePointAt(<i>k</i>) == ch) && (<i>k</i> >= fromIndex)     * </pre></blockquote>     * is true. In either case, if no such character occurs in this     * string at or after position <code>fromIndex</code>, then     * <code>-1</code> is returned.     *     * <p>     * There is no restriction on the value of <code>fromIndex</code>. If it     * is negative, it has the same effect as if it were zero: this entire     * string may be searched. If it is greater than the length of this     * string, it has the same effect as if it were equal to the length of     * this string: <code>-1</code> is returned.     *     * <p>All indices are specified in <code>char</code> values     * (Unicode code units).     *     * @param   ch          a character (Unicode code point).     * @param   fromIndex   the index to start the search from.     * @return  the index of the first occurrence of the character in the     *          character sequence represented by this object that is greater     *          than or equal to <code>fromIndex</code>, or <code>-1</code>     *          if the character does not occur.     */    public int indexOf(int ch, int fromIndex) {int max = offset + count;char v[] = value;if (fromIndex < 0) {    fromIndex = 0;} else if (fromIndex >= count) {    // Note: fromIndex might be near -1>>>1.    return -1;}int i = offset + fromIndex;if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {    // handle most cases here (ch is a BMP code point or a    // negative value (invalid code point))    for (; i < max ; i++) {if (v[i] == ch) {    return i - offset;}    }    return -1;}if (ch <= Character.MAX_CODE_POINT) {    // handle supplementary characters here    char[] surrogates = Character.toChars(ch);    for (; i < max; i++) {if (v[i] == surrogates[0]) {    if (i + 1 == max) {break;    }    if (v[i+1] == surrogates[1]) {return i - offset;    }}    }}return -1;    }</span>


从fromIndex开始但包括fromIndex。
System.out.println("s19.indexOf('l',3):" + s19.indexOf('l',3));

输出:s19.indexOf('l',3):3

int indexOf(String str,intfrom Index)与上类似。


String substring(intstart)

<span style="font-size:18px;">    /**     * Returns a new string that is a substring of this string. The     * substring begins with the character at the specified index and     * extends to the end of this string. <p>     * Examples:     * <blockquote><pre>     * "unhappy".substring(2) returns "happy"     * "Harbison".substring(3) returns "bison"     * "emptiness".substring(9) returns "" (an empty string)     * </pre></blockquote>     *     * @param      beginIndex   the beginning index, inclusive.     * @return     the specified substring.     * @exception  IndexOutOfBoundsException  if     *             <code>beginIndex</code> is negative or larger than the     *             length of this <code>String</code> object.     */    public String substring(int beginIndex) {return substring(beginIndex, count);    }</span>


System.out.println("s19.substring(5):" + s19.substring(5));

输出:s19.substring(5):World

System.out.println("s19.substring(10):" + s19.substring(10));

输出:s19.substring(10):


String substring(intstart,intend)

<span style="font-size:18px;">    /**     * Returns a new string that is a substring of this string. The     * substring begins at the specified <code>beginIndex</code> and     * extends to the character at index <code>endIndex - 1</code>.     * Thus the length of the substring is <code>endIndex-beginIndex</code>.     * <p>     * Examples:     * <blockquote><pre>     * "hamburger".substring(4, 8) returns "urge"     * "smiles".substring(1, 5) returns "mile"     * </pre></blockquote>     *     * @param      beginIndex   the beginning index, inclusive.     * @param      endIndex     the ending index, exclusive.     * @return     the specified substring.     * @exception  IndexOutOfBoundsException  if the     *             <code>beginIndex</code> is negative, or     *             <code>endIndex</code> is larger than the length of     *             this <code>String</code> object, or     *             <code>beginIndex</code> is larger than     *             <code>endIndex</code>.     */    public String substring(int beginIndex, int endIndex) {if (beginIndex < 0) {    throw new StringIndexOutOfBoundsException(beginIndex);}if (endIndex > count) {    throw new StringIndexOutOfBoundsException(endIndex);}if (beginIndex > endIndex) {    throw new StringIndexOutOfBoundsException(endIndex - beginIndex);}return ((beginIndex == 0) && (endIndex == count)) ? this :    new String(offset + beginIndex, endIndex - beginIndex, value);    }</span>

System.out.println("s19.substring(5,6):" + s19.substring(5,6));//包左不包右

输出:s19.substring(5,6):W

System.out.println("s19.substring(-1,6):" + s19.substring(-1,6));

输出:Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1

System.out.println("s19.substring(5,20):" + s19.substring(5,20));

输出:Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 20




0 0