主要是练习String类中indexOf的用法

/**
 * 查找一个字符串在另一个字符串中出现的次数
 */
public class MainTest {
    public static void main(String[] args) {
        int count = countSubString("hello java", "a");
        System.out.println(count);
    }

    // countSubString,来返回字符串出现的个数
    public static int countSubString(String string,String subString){
        // 定义一个count来存放字符串出现的次数
        int count = 0 ;
        // 调用String类的indexOf(String str)方法,返回第一个相同字符串出现的下标
        while (string.indexOf(subString) != -1){
            count ++ ;
            int index = string.indexOf(subString);
            //将长的那个字符串做截取
            string = string.substring(index+1);
        }
        return count;
    }
}

indexOf源码解析 https://www.jianshu.com/p/42cdd8d5ba2e

相关文章:

  • 2021-10-11
  • 2022-12-23
  • 2022-12-23
  • 2022-02-02
  • 2022-12-23
  • 2022-01-28
  • 2022-12-23
  • 2021-10-05
猜你喜欢
  • 2021-11-22
  • 2022-12-23
  • 2021-07-21
  • 2022-01-26
  • 2020-04-30
  • 2021-12-28
相关资源
相似解决方案