黑马程序员技术交流社区

标题: 面试模拟题分享,含答案 [打印本页]

作者: jeremyl    时间: 2016-6-2 18:12
标题: 面试模拟题分享,含答案
现有一串字符串 "上海传智播客,上海黑马,武汉传智播客,深圳黑马,北京传智播客,广州黑马,北京黑马" ,
要求使用程序统计出"传智播客"和"黑马"在该字符串中出现的次数,然后按照指定格式输出到当前项目下的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;
        }

}



作者: LBBQ    时间: 2016-6-3 00:06
学习了,一起加油吧,哈哈
作者: kevinlbq    时间: 2016-6-3 00:31
又学到一招,很好的东西




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2