2. 编写一个程序,输出在一个字符串中,指定的字符串出现的次数
第一种方法:
public class Test { public static void main(String[] args) { String s = "sunjava786$$%^*()Javajsdgkjavakh457-=javaqw213%%!!"; String s0 = "java"; int count = 0; int index = -1; while((index = s.indexOf(s0))!=-1){ s = s.substring(index + s0.length()); count++; } System.out.println("count: "+count); } }// count: 3
第二种方法:
public class Test { public static void main(String[] args) { String ss = "sunjava786$$%^*()Javajsdgkjavakh457-=javaqw213%%!!"; String s0 = "java"; int count = 0; int index = 0; int startPos = 0; while(index != -1){ index = ss.indexOf(s0,startPos); startPos = index + s0.length(); // 或者 index = ss.indexOf(s0,index + s0.length()) if(index != -1){ count = count + 1; } } System.out.println("count:"+count); } }// 3