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

这段代码变量定义的有点多了
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+"次");
        }
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马