public class Test { public static int count(String text,String sub){ int count =0, start =0; while((start=text.indexOf(sub,start))>=0){ start += sub.length(); count ++; } return count; } public static void main(String[] args){ String text ="nihaoksdoksad"; String sub ="o k"; System.out.println(count(text,sub)); } }