A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© jeremyl 中级黑马   /  2016-6-2 18:12  /  788 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

现有一串字符串 "上海传智播客,上海黑马,武汉传智播客,深圳黑马,北京传智播客,广州黑马,北京黑马" ,
要求使用程序统计出"传智播客"和"黑马"在该字符串中出现的次数,然后按照指定格式输出到当前项目下的times.txt中
------------------------------------------------------------------------------
下面是答案:大家可以先自己做做啊
        public static void main(String[] args) throws IOException {
                // 1.把大的字符串定义出来
                String str = "上海传智播客,上海黑马,武汉传智播客,深圳黑马,北京传智播客,广州黑马,北京黑马";
                // 2.需要在大字符串中查找的小字符串s1和s2
                String s1 = "传智播客";
                String s2 = "黑马";

                int count1 = getCount(str, s1);// 查找到的"传智播客"出现的次数
                int count2 = getCount(str, s2);// 查找到的"黑马"出现的次数

                StringBuilder sb = new StringBuilder();
                sb.append(s1).append("=").append(count1).append("次,").append(s2)
                                .append("=").append(count2).append("次");
               
              String string=s1+"="+count1+"次,"+s2+"="+count2+"次";      //这是ling
               
               
                //调用方法,把字符串写到文件中
                write2File(sb.toString());
        }


        /**
         * 定义一个方法,把字符串内容写到当前项目下的times.txt文件中
         * 1.返回值类型: void
         * 2.参数列表:String
         * @throws IOException
         */
       
        public static void write2File(String str) throws IOException{
                FileWriter fw=new FileWriter("times.txt");
                fw.write(str);
                fw.close();
        }
       

        /**
         * 定义一个方法,传入大字符串和小字符串,这个方法可以自动完成在大字符串中查找小字符串出现的次数
         *  1.返回值类型: int
         *  2.参数列表:
         * String bigStr,String minStr
         */

        public static int getCount(String bigStr, String minStr) {
                int count = 0;
                Pattern p = Pattern.compile(minStr);
                Matcher m = p.matcher(bigStr);
                while (m.find()) {
                        count++;
                }
                return count;
        }

}


评分

参与人数 4黑马币 +16 收起 理由
kevinlbq + 3
LBBQ + 5 很给力!
GAREN + 3 很给力!
a382541804 + 5 赞一个!

查看全部评分

2 个回复

倒序浏览
学习了,一起加油吧,哈哈
回复 使用道具 举报
又学到一招,很好的东西
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马