zoukankan      html  css  js  c++  java
  • Java 获取一个字符串中,另一个字符串出现的次数

    Java 获取一个字符串中,另一个字符串出现的次数

    思想:

    1. indexOf到字符串中到第一次出现的索引
    2. 找到的索引+被找字符串长度,截取字符串
    3. 计数器++

    代码实现:

     1 public class Test {
     2     public static void main(String[] args) {
     3         String str="helloword";
     4         fun(str,"hello");
     5     }
     6     public static void fun(String str,String m){
     7         //m代表字符的长度        
     8         int count=0;
     9         while(str.indexOf(m)>=0){
    10             int index=str.indexOf(m)+m.length();//获取每次找到之后的下标位置
    11             str=str.substring(index);
    12             count++;
    13         }
    14         System.out.println("指定字符串在原字符中出現:"+count+"次");
    15     }
    16 }

    总结:最开始就是不明白为什么需要加上字符串的长度

  • 相关阅读:
    12.1
    11.26
    12.5Java日报
    11.25
    11.27
    12.03
    11.28
    12.04
    如何在TortoiseGit中使用sshkeygen生成的key
    leetcode 39 组合总和
  • 原文地址:https://www.cnblogs.com/yanpingping/p/10553931.html
Copyright © 2011-2022 走看看