String.indexOf()的使用方法


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM