zoukankan      html  css  js  c++  java
  • 13. Java 获取指定字符串出现的次数

    方式一
    /**
     * @param args
     */
    public static void main(String[] args) {
    
        String srcText = "Hello World";
        String findText = "e";
        int num = appearNumber(srcText, findText);
        System.out.println(num);
    }
    
    /**
     * 获取指定字符串出现的次数
     * 
     * @param srcText 源字符串
     * @param findText 要查找的字符串
     * @return
     */
    public static int appearNumber(String srcText, String findText) {
        int count = 0;
        Pattern p = Pattern.compile(findText);
        Matcher m = p.matcher(srcText);
        while (m.find()) {
            count++;
        }
        return count;
    }
     
    方法二
    /**
     * @param args
     */
    public static void main(String[] args) {
    
        String srcText = "Hello World";
        String findText = "e";
        int num = appearNumber(srcText, findText);
        System.out.println(num);
    }
    
    
    /**
     * public int indexOf(int ch, int fromIndex)
     * 返回在此字符串中第一次出现指定字符处的索引,从指定的索引开始搜索
     * 
     * @param srcText
     * @param findText
     * @return
     */
    public static int appearNumber(String srcText, String findText) {
        int count = 0;
        int index = 0;
        while ((index = srcText.indexOf(findText, index)) != -1) {
            index = index + findText.length();
            count++;
        }
        return count;
    }

      

     
  • 相关阅读:
    Python中 sys.argv[]的用法简明解释
    python多线程
    python 多进程
    shell----bash
    linux crontab
    Elastic search 概述
    Elastic search 入门
    Elastic search CURL命令
    Elastic search 基本使用
    Elastic search 字段折叠 collaose
  • 原文地址:https://www.cnblogs.com/zkx4213/p/11058507.html
Copyright © 2011-2022 走看看