黑马程序员技术交流社区

标题: 呼呼。。。走过路过不要错过 [打印本页]

作者: gss    时间: 2015-9-18 23:05
标题: 呼呼。。。走过路过不要错过
package StringPackage;

/*一个字串在整串中出现的次数
* 1要找字串是否存在,如果存在获取出现的位置可以用indexof完成
* 2如果找到了那么记录出现的位置并在剩余的字符串中继续查找该字串而剩余的字符串的起始位置+字串的长度
* 3通过循环完成查找,如果找不到就是-1.并对每次找的用计数器记录
*
*
*
* */
public class StringClass3 {

        public static void main(String[] args) {
                // TODO Auto-generated method stub
                String str = "abndfjssyaahgaja";
                String key = "a";
                int count2 = getKeyStringCount(str, key);
                int count1 = getKeyStringCount2(str, key);
                System.out.println(count1);
                System.out.println(count2);

        }

        public static int getKeyStringCount2(String str, String key) {
                // TODO Auto-generated method stub
                int count = 0;
                int index = 0;
                while ((index = str.indexOf(key, index)) != 1) {
                        index = index + key.length();
                        count++;

                }
                return count;
        }

        public static int getKeyStringCount(String str, String key) {
                // TODO Auto-generated method stub
                // 定义计数器
                int count = 0;
                // 定义变量记录key出现的位置
                int index = 0;
                while ((index = str.indexOf(key)) != -1) {
                        str = str.substring(index + key.length());
                        count++;

                }
                return count;
        }

}

作者: 俏皮雅轩    时间: 2015-9-18 23:07
数组,返回值




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