1、查找某个字符在字符串中第几次出现的位置

    /**
     * 查找某个字符在字符串中第几次出现的位置
     * @param string 要匹配的字符串
     * @param i 第几次出现
     * @param character 要匹配的字符
     * @return 出现的位置
     */
    public static int getCharacterPosition(String string ,int i,String character){  
        // Matcher slashMatcher = Pattern.compile("/").matcher("hahah/hhh/af");  
        Matcher slashMatcher = Pattern.compile(character).matcher(string);  
        int mIdx = 0; 
        //如果没有匹配的则返回-1
        int result=-1;
        while(slashMatcher.find()) {  
            mIdx++;  
            if(mIdx == i){
                //将匹配的结果返回
                result = slashMatcher.start();
                break;  
            }  
        }  
        return result;  
    }

2、查找某个字符在字符串中出现的次数

/**
     * 查找某个字符在字符串中出现的次数
     * @param str 字符串
     * @param token 某个字符
     * @return 出现的次数
     */
    public static int countToken(String str,String token){
        int count=0;
        while(str.indexOf(token)!=-1){
            count++;
            str = str.substring(str.indexOf(token)+token.length());
        }
        return count;
    }

 

posted on 2017-08-03 19:54  zhangjinru123  阅读(115)  评论(0编辑  收藏  举报