黑马程序员技术交流社区

标题: 判断一个字符串含有某个子字符串的个数 [打印本页]

作者: li--yong    时间: 2016-8-18 18:03
标题: 判断一个字符串含有某个子字符串的个数
import java.util.Scanner;

public class Text01 {
        public static void main(String[] args) {
                Scanner sc = new Scanner(System.in);
               
                System.out.println("请输入一个字符串:");
                String enters= sc.nextLine();
                System.out.println("请输入一个子字符串:");
                String enters2= sc.nextLine();
               
                 int re = re(enters,enters2);
                 System.out.println("第一个字符串含有所输入子字符串的个数为:"+re);
        }

        public static int re(String st1, String st2) {
               
                int le = st2.length();
                int count = 0;
                boolean flag = true;
                while (flag) {

                        if (st1.contains(st2)) {
                                int num = st1.indexOf(st2);
                                 st1 = st1.substring(num + le );
                                count++;
                                flag = true;
                        }else{
                               
                                flag=false;
                        }
                }
                return count;
        }
       
}
作者: aliali007    时间: 2016-8-18 19:18
楼主的意思我明白,加些注释就更好啦




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