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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© liujian5461267 中级黑马   /  2016-5-9 09:48  /  314 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

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

1 个回复

倒序浏览
顶一个,加油
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马