今天一个同学对我说老师布置了一个作业让编写一个计算字符串中子串出现的次数的程序,接下来吾爱编程就为大家介绍一下计算字符串中子串出现的次数的方法,有需要的小伙伴可以参考一下:
1、题目如下:
输入两个字符串,计算第二个字符串在以一个字符串出现的次数
2、程序代码:public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("输入字符串:");
String str = sc.nextLine();
System.out.println("输入子字符串:");
String substr= sc.nextLine();
int count = 0, pos = 0;
while (str.indexOf(substr, pos) >= 0 && pos
count++;
pos = str.indexOf(substr, pos) + substr.length(); // 得到新的start值。
}
System.out.println("子串出现的次数" + count);
}
以上就是吾爱编程为大家介绍的关于java计算字符串中子串出现的次数的方法,了解更多相关文章请关注吾爱编程网!