题目:计算字符串中子串出现的次数
1 public class _049CountString { 2 3 public static void main(String[] args) { 4 countString(); 5 } 6 7 private static void countString() { 8 Scanner s = new Scanner(System.in); 9 System.out.print("请输入字符串:"); 10 String str1 = s.nextLine(); 11 System.out.print("请输入子串:"); 12 String str2 = s.nextLine(); 13 int count = 0; 14 if (str1.equals("") || str2.equals("")) { 15 System.out.println("你没有输入字符串或子串,无法比较!"); 16 System.exit(0); 17 } else { 18 for (int i = 0; i <= str1.length() - str2.length(); i++) { 19 if (str2.equals(str1.substring(i, str2.length() + i))) 20 // 这种比法有问题,会把"aaa"看成有2个"aa"子串。 21 count++; 22 } 23 System.out.println("子串在字符串中出现: " + count + " 次"); 24 } 25 26 } 27 28 }