Java经典习题49

/*
题目:计算字符串中子串出现的次数。
*/
//使用动态规划吗?
//1)找子串 (函数1);2)确定子串长度(函数2);3)寻找子串出现的次数。

import java.util.*;

public class Class49 {

public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("请输入字符串:");
String str1 = sc.nextLine();
System.out.println("请输入子串:");
String str2 = sc.nextLine();
int count = 0;
if(str1.equals(" ") || str2.equals(" ")){
System.out.println("你没有输入字符串或子串");
System.exit(0);
}else{
for(int i = 0; i <= str1.length() - str2.length(); i++){
if(str2.equals(str1.substring(i, str2.length() + i))){
count++;
}
}
}
System.out.println("子串在字符串中出现:" + count);

}
}

原文地址:https://www.cnblogs.com/zhuozige/p/12358858.html