• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
cp3
博客园    首页    新随笔    联系   管理    订阅  订阅

java实现字符统计及其子字符串的统计

public class TestCount{
    //测试代码
    public static void main(String[] args){
        String s="java I Love  JAVA,我是迪锐2010年的学员!It's so difficult to study java";
        count(s);//调用方法
        System.out.println("======================");
        find(s,"java");//调用方法
    }
    //字符统计代码
    public static void count(String s){
        int count1=0;//统计小写字母的个数
        int count2=0;//统计大写字母的个数
        int count3=0;//统计非字母的个数

        for(int i=0;i<s.length();i++){
            char a=s.charAt(i);
            if(a>'a'&&a<'z'){
                count1++;
            }
            if(a>'A'&&a<'Z'){
                count2++;
            }
            else{
                count3++;
            }
        }

        System.out.println("小写字母数为: "+count1);
        System.out.println("大写字母数为: "+count2);
        System.out.println("非字母数为: "+count3);
    }
    //测试字符串中某字串出现的个数
    public static void find(String s,String subs){
        int count=0;
       
        while(s!=null&&s.length()>=subs.length()){
          
            int n=s.indexOf(subs);//找到第一个字串出现的位置
            if(n>=0){//如果有相应字串,则执行一下代码
                count++;
                s=s.substring(n+1);
            }else{//如果找不到,就退出
                break;
            }
        }
        System.out.println(subs+": 出现的次数为:"+count);
    }
}

posted @ 2010-10-16 15:59  cp3  阅读(1336)  评论(1)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3