indexOf方法 在一个字符串中查找另一个字符串的次数

/** 
 * "In the entire world there's nobody like me. 
 *Since the beginning of time, there has never been another person like me. 
 *Nobody has my smile. 
 *Nobody has my eyes, my nose, my hair, my hands, or my voice."
 * 要求:算出my在这段话中出现的次数?
 * 我的思路:
 * 1.寻找一个字符串短语在一段字符串中出现几次,首先肯定是用str.indexOf("my",start)方法
 * 2.indexOf方法的返回值是int,如果找不到就会返回-1
 * 3.利用这一点,可以设定一个循环,并定义一个计数器,
 * 让计算机从段落的起始,一直找到末尾,如果找到一个就计数器+1,直到indexof返回结果为-1时,
 * 停止循环.
 * 4.注意:每一次开始找的位置,是不确定的.每一次的新位置,都是上一次找到"短语的位置"+"短语的长度"
 */
public class IndexDemo {
 public static void main(String[] args) {
  Scanner scan = new Scanner(System.in);
  String str = "In the entire world there's nobody like me. "
    + "\nSince the beginning of time, "
    + "there has never been another person like me."
    + "\nNobody has my smile. \nNobody has my eyes, "
    + "my nose, my hair, my hands, or my voice.";
  int count = 0;
  System.out.println("请输入需要查找的单词:");
  String key = scan.next();
  count = serachWord(str,key);
  System.out.println("短语my在段落中出现"+count+"次");
 }
 
 /**
  * 查找某个单词在段落中出现次数的方法
  * @param str 
  * @return
  */
 /**
  * @param str
  * @param key
  * @return
  */
 public static int serachWord(String str,String key) {
  //记录查找次数
  int count = 0;
  //记录每次查找的下标位置,初始化
  int index = 0;
  //定义循环,如果index的位置不是-1,就一值查找
  while((index = str.indexOf(key,index))!=-1){
   
   //每循环一次就要明确下一次查找的位置
   index = index+key.length();
   //每查找一次计数器自增
   count ++;
  }
  return count;
 }
}

转载于:https://my.oschina.net/zyjcxc/blog/667304

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值