查询字符串中特殊字符出现的次数

/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
 */

package com.huawei.hmnewexperience.util;

/**
 * @description: 字符串工具类
 * @fileName: com.huawei.hmnewexperience.util.StringUtil
 * @author: WWX1062477
 * @date: 2021-12-27 17:06
 */
public class StringUtil {

    /**
     * 获取字符串中特殊字符出现的次数
     *
     * @param str the str
     * @param key the key
     * @return the count
     */
    public static int getCount(String str, String key) {
        if (str == null || key == null || "".equals(str.trim()) || "".equals(key.trim())) {
            return 0;
        }
        int count = 0;
        int index = 0;
        while ((index = str.indexOf(key, index)) != -1) {
            index = index + key.length();
            count++;
        }
        return count;
    }

    public static void main(String[] args) {
        System.out.println(getCount(",158,528,9,844,", ","));
    }
}

 

posted @ 2022-01-13 16:08  WPMA  阅读(111)  评论(0)    收藏  举报