system_esc

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
比如:javascriptjavasejavaeejavame

思路:
    定义一个计数器
    获取java第一次出现的位置
    从第一次出现位置后剩余的字符 串中继续获取java出现的位置每获取一次就计数一次
    当获取不到时,计数完成

复制代码
class StringCount{
    public static void main(String[] args){
        String s = "javascriptjavasejavaeejavame";
        int count = getSubString(s,"java");
        System.out.println(count);
    }
    public static int  getSubString(String str,String key){
        int count = 0;
        int index = 0;
        while((index=str.indexOf(key,index))!=-1){
            index = index+key.length();
            count++;
        }
        return count;
    }
    
}
复制代码

第二种方式:

复制代码
 1 public static int getSubCount_2(String str,String key){
 2     int count = 0;
 3     int index = 0;
 4 
 5     while ((index=str.indexOf(key,index))!=-1){
 6         str = str.subtring(index+key.length());
 7         count++;
 8     }
 9     return count;
10 }
posted on 2014-01-13 15:36  system_esc  阅读(258)  评论(0编辑  收藏  举报