Contents

Methods For Match Substring

Using regular expression (RECOMMEND)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14

private int pattern(String str, String reg) {
        Pattern pattern = Pattern.compile(reg);
  
        // Create a matcher for the input String
        Matcher matcher = pattern.matcher(str);
  
        int count = 0;
        while (matcher.find()) {
        	count ++;
        }
        
        return count;
	}

Using indexOf() and substring and recuesion

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11

    private void index(String text){
        int indexs = text.indexOf("cs");
        if(indexs != -1){ // means have substring
            count++;
            if(indexs < text.length() - 1){ 
                text = text.substring(indexs + 1);
                index(text);
            }
        }
    }