首页 > 技术文章 > String.indexOf()的使用方法

andrew-303 2019-10-11 10:20 原文

String.indexOf()的用途:

返回此字符串中第一个出现的指定的子字符串,如果没有找到则返回-1

 

源码如下:

/**
* Returns the index within this string of the first occurrence of the
* specified substring.
*
* <p>The returned index is the smallest value <i>k</i> for which:
* <blockquote><pre>
* this.startsWith(str, <i>k</i>)
* </pre></blockquote>
* If no such value of <i>k</i> exists, then {@code -1} is returned.
*
* @param str the substring to search for.
* @return the index of the first occurrence of the specified substring,
* or {@code -1} if there is no such occurrence.
*/
public int indexOf(String str) {
        return indexOf(str, 0);
    }

举例1:包含指定子字符串的情况

String str1="abcdef";
String str2="cd";
System.out.println(str1.indexOf(str2));

输出结果:2

举例2:未包含指定子字符串的情况

String str1="abcdef";
String str2="gh";
System.out.println( str1.indexOf(str2) );

输出结果:-1

 

它还有一个重载的方法:从指定的索引开始,返回此字符串中第一个出现的指定的子字符串,如果没有找到则返回-1

源码如下:

/**
     * Returns the index within this string of the first occurrence of the
     * specified substring, starting at the specified index.
     *
     * <p>The returned index is the smallest value <i>k</i> for which:
     * <blockquote><pre>
     * <i>k</i> &gt;= fromIndex {@code &&} this.startsWith(str, <i>k</i>)
     * </pre></blockquote>
     * If no such value of <i>k</i> exists, then {@code -1} is returned.
     *
     * @param   str         the substring to search for.
     * @param   fromIndex   the index from which to start the search.
     * @return  the index of the first occurrence of the specified substring,
     *          starting at the specified index,
     *          or {@code -1} if there is no such occurrence.
     */
    public int indexOf(String str, int fromIndex) {
        return indexOf(value, 0, value.length,
                str.value, 0, str.value.length, fromIndex);
    }

举例3:从指定的索引开始,包含指定子字符串的情况

1 String str3="abcdef0abcdef";
2 String str4="cd";
3 System.out.println( str3.indexOf(str4,5) );

输出结果:9

举例3:从指定的索引开始,未包含指定子字符串的情况

String str3="abcdef0abcdef";
String str4="gh";
System.out.println( str3.indexOf(str4,5) );

输出结果:-1

推荐阅读