1. 程式人生 > >判斷字串s中有多少s1

判斷字串s中有多少s1

//判斷字串s中有多少s1,
//s=aaa,s1=aa,則輸出1,而不是2
public static int countK2(String s, String s1) {
        if (s == null || s1 == null) {
            return 0;
        }
        int count = 0;
        int len = s1.length();

        for (int i = 0; i < s.length();i++ ) {
            if (i + len > s.length()) {//超過最大長度了
                return
count; } else {//佛則繼續比較 if (s.charAt(i) == s1.charAt(0)) { for (int j = 1; j < s1.length(); j++) { if (s.charAt(i + j) != s1.charAt(j)) {//不等,下一個i++ break; } if
(j == s1.length() - 1) {//找到了,直接跳過這個s1長度 count++; i=i+len-1;//本來直接i=i+len開始遍歷,但是外層for迴圈i++了,所以要i=i+len-1; } } } } } return count; } /* //判斷字串s中有多少s1,如aaa 有 3
個a, public static int countK(String s, String s1) { if (s == null || s1 == null) { return 0; } int count = 0; int len = s1.length(); for (int i = 0; i < s.length(); i++) { if (i + len > s.length()) {//超過最大長度了 return count; } else {//佛則繼續比較 if (s.charAt(i) == s1.charAt(0)) { for (int j = 1; j < s1.length(); j++) { if (s.charAt(i + j) != s1.charAt(j)) { break; } if (j == s1.length() - 1) { count++; } } } } } return count; }*/