zoukankan      html  css  js  c++  java
  • 统计字符串中某个字符的出现次数

    引言:统计字符串中某个字符的出现次数其实可以直接使用apache commons lang包中的StringUtils.countMatches()方法,但觉得写的有点麻烦了,就自己实现了一个完成类似功能简单的方法

    1. 不废话,先代码:

    1、TestCountMatches 类:

    package test;
    
    public class TestCountMatches {
    
        public static void main(String[] args) {
            System.out.println(countMatched("abcdeeeee", "e"));
            System.out.println(countMatched("abcdeeab", "ab"));
        }
    
        /**
         * 统计出现次数
         * @param string 目标字符串
         * @param sub 目标子字符串
         * @return
         */
        public static int countMatched(String string, String sub){
            //判空,为空直接返回0,表示不存在
            if(StringUtil.isEmpty(string) || StringUtil.isEmpty(sub)){
                return 0;
            }
            int count = 0;
            int index;
            // 循环一次将出现的字符串索引向后移一位,计数器+1,并截取原字符串索引+1的字符串,
            // 如“abcdeeeee”第一次循环找到“e”索引4,substring(4+1)方法截取后得到新的字符串“eeee”,
            // 循环第二次找到“e”的索引0,substring(0+1)方法截取后得到新的字符串“eee”,,,以此类推
            while((index = string.indexOf(sub)) > -1){
                count++;
                string = string.substring(index + 1);
            }
            return count;
        }
    
    }
    

    2、StringUtil工具类:

    package test;
    
    public class StringUtil {
    
        /**
         * 判断字符串是否为空
         * @param string
         * @return
         */
        public static boolean isEmpty(String string){
            if(string == null || "".equals(string.trim())){
                return true;
            }
            return false;
        }
    
    }
    

    运行结果

    2. 再看一下Apache 提供的工具类apache commons lang方法countMatches():

    public static int countMatches(final CharSequence str, final CharSequence sub) {
            if (isEmpty(str) || isEmpty(sub)) {
                return 0;
            }
            int count = 0;
            int idx = 0;
            while ((idx = CharSequenceUtils.indexOf(str, sub, idx)) != INDEX_NOT_FOUND) {
                count++;
                idx += sub.length();
            }
            return count;
        }
    

    其实思路差不多,理解了最好自己动手写一下

  • 相关阅读:
    为什么构造函数不能声明为虚函数,析构函数可以
    _stdcall,_cdecl区别
    C++的dllexport和dllimport
    什么样的代码才是好代码
    苦逼三流小公司程序员这半年找工作经历(3)——选择offer
    c# DataTable、DataSet、DataReader
    C# 定时器
    sql 中如何将返回的记录某一条置顶
    c# devExpress控件 comboBoxEdit,gridControl1,labelcontrol、xtraReports ,ButtonEdit,dateEdit
    c# 公共方法
  • 原文地址:https://www.cnblogs.com/wang-zai/p/7799695.html
Copyright © 2011-2022 走看看