java String.indexOf方法在一个字符串中查找另一个字符串的次数的简单应用

 01
  
  /**
  
  02
  
  *"In the entirehttp://zzdxjyzd.com world there's nobody like me.
  
  03
  
  *Since the beginning of time, there has never been another person like me.
  
  04
  
  *Nobody has my smile.
  
  05
  
  *Nobody has my eyes, my nose, my hair, my hands, or my voice."
  
  06
  
  * 要求:用户输入一个单词,求出在这段话中出现的次数?
  
  07
  
  08
  
  * 我的思路:
  
  09
  
  * 1.寻找一个字符串短语在一段字符串中出现几次,首先肯定是用str.indexOf("my",start)方法
  
  10
  
  * 2.indexOf方法的返回值是int,如果找不到就会返回-1
  
  11
  
  * 3.利用这一点,可以设定一个循环,并定义一个计数器,
  
  12
  
  * 让计算机从段落的起始,一直找到末尾,如果找到一个就计数器+1,直到indexof返回结果为-1时,
  
  13
  
  * 停止循环.
  
  14
  
  * 4.注意:每一次开始找的位置,是不确定的.每一次的新位置,都是上一次找到"短语的位置"+"短语的长度"
  
  15
  
  */
  
  16
  
  public class IndexDemo {
  
  17
  
  18
  
  public static void main(String[] args) {
  
  19
  
  Scanner scan = new Scanner(System.in);
  
  20
  
  String str = "In the entire world there's nobody like me. "
  
  21
  
  + "\nSince the beginning of time, "
  
  22
  
  + "there has never been another person like me."
  
  23
  
  + "\nNobody has my smile. \nNobody has my eyes, "
  
  24
  
  + "my nose, my hair, my hands, or my voice.";
  
  25
  
  int count = 0;
  
  26
  
  System.out.println("请输入需要查找的单词:");
  
  27
  
  String key = scan.next();
  
  28
  
  count = serachWord(str,key);
  
  29
  
  System.out.println("短语my在段落中出现"+count+"次");
  
  30
  
  }
  
  31
  
  32
  
  33
  
  /**
  
  34
  
  * 查找某个单词在段落中出现次数的方法
  
  35
  
  * @param str
  
  36
  
  * @return
  
  37
  
  */
  
  38
  
  /**
  
  39
  
  * @param str
  
  40
  
  * @param key
  
  41
  
  * @return
  
  42
  
  */
  
  43
  
  public static int serachWord(String str,String key) {
  
  44
  
  //记录查找次数
  
  45
  
  int count = 0;
  
  46
  
  //记录每次查找的下标位置,初始化
  
  47
  
  int index = 0;
  
  48
  
  //定义循环,如果index的位置不是-1,就一值查找
  
  49
  
  while((index = str.indexOf(key,index))!=-1){
  
  50
  
  51
  
  //每循环一次就要明确下一次查找的位置
  
  52
  
  index = index+key.length();
  
  53
  
  //每查找一次计数器自增
  
  54
  
  count ++;
  
  55
  
  }
  
  56
  
  return count;
  
  57
  
  }
  
  58
  
  }

转载于:https://www.cnblogs.com/dakunqq/p/11484460.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值