Java查找一個字符串在另一個字符串中出現的次數


主要是練習String類中indexOf的用法

/**
 * 查找一個字符串在另一個字符串中出現的次數
 */
public class MainTest {
    public static void main(String[] args) {
        int count = countSubString("hello java", "a");
        System.out.println(count);
    }

    // countSubString,來返回字符串出現的個數
    public static int countSubString(String string,String subString){
        // 定義一個count來存放字符串出現的次數
        int count = 0 ;
        // 調用String類的indexOf(String str)方法,返回第一個相同字符串出現的下標
        while (string.indexOf(subString) != -1){
            count ++ ;
            int index = string.indexOf(subString);
            //將長的那個字符串做截取
            string = string.substring(index+1);
        }
        return count;
    }
}

indexOf源碼解析 https://www.jianshu.com/p/42cdd8d5ba2e


免責聲明!

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



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