黑马程序员技术交流社区

标题: 计算大字符串中小字符串出现的次数 [打印本页]

作者: 徐慧shanghai    时间: 2015-10-14 09:25
标题: 计算大字符串中小字符串出现的次数
这段代码变量定义的有点多了
public class StringDemo {
        public static void main(String[] args) {
                Scanner sc = new Scanner(System.in);
                System.out.println("请输入一串字符:");
                String str = sc.nextLine();
                System.out.println("请输入子串");
                String zs = sc.nextLine();
                StringBuilder sb = new StringBuilder(str);
                int x = 0;
                int y = -1;
                int count = 0;
                int len = zs.length();
                while (x < str.length()) {
                        y = sb.indexOf(zs,x);
                        if(y != -1) {
                                count++;
                                x = len+y;
                        }else{
                                break;
                        }
                }
                System.out.println("子串在字符串中出现的次数为"+count+"次");
        }
}





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