用Java编写代码,统计某个字符串中某个字符串出现的次数,例如,统计
String str=”This apple is a red apple. ”;
中 “apple”出现的次数。

解决方案 »

  1.   

    int count=0;
    String str = "apple";
    String s = "This apple is a red apple";
    int index = s.indexOf(str);
    while(index != -1) {
    count++;
    s = s.substring(index + str.length());
    index =s.indexOf("apple");
    }
    System.out.println(count);
      

  2.   

     
    String s = "This apple is a red apple";
     Stirng s1 = "apple";
            int index = -1;
            while((index = s.indexOf(s1))!=-1) {
            count++;
            s = s.substring(index + s1.length());
            
            }
            System.out.println(count);
    推荐你去看一下马士兵老师的视频  里面讲得不错  我也是初学者 呵呵 加油哈!!
      

  3.   

      String str = "This apple is a red apple";
     Stirng s = "apple";
            int index = -1;
            while((index = str.indexOf(s))!=-1) {
            count++;
            str = str.substring(index + s.length());
            
            }
            System.out.println(count);
    多看java文档,里面有你不会和不知道的方法
      

  4.   


    顶4楼,但要完善下,如下:int wordNumb=strArrage.length -1;
    if(str.endsWith("apple")) wordNumb++;
      

  5.   

    上面贴少了。String str="apple This apple is a red apple";
    String[] strArrage=str.split("apple");
    int wordNumb=strArrage.length -1;
    if(str.endsWith("apple")) wordNumb++;
      

  6.   

    上面贴少了。String str="apple This apple is a red apple";
    String[] strArrage=str.split("apple");
    int wordNumb=strArrage.length -1;
    if(str.endsWith("apple")) wordNumb++;
      

  7.   

    public class CountIt {
    public static void main (String args []) {
    int count = 0;
    String s = "apple";
    String str = "This apple is a red apple that LZ gives me!";
    int index = 1;
    while (index!=-1) {

    str = str.substring(index + s.length());
    index = str.indexOf(s);
    count++;
    }
    System.out.println(count);
    }}
      

  8.   


    split可以设置的s.split(subStr,-1).length-1;