获取目标字符串在字符串中第N次出现的位置

  /**
     * 获取目标字符串在字符串中第N次出现的位置
     * @file name
     * @author xiehongwei
     * @date 2017-8-2 下午3:29:09
     * @param source    源字符串
     * @param target    目标字符串
     * @param n         出现位置
     * @return
     */
    public static int getCharacterPosition(String source, String target, int n) {
        // 这里是获取目标符号的位置
        Matcher slashMatcher = Pattern.compile(target).matcher(source);
        int mIdx = 0;
        while (slashMatcher.find()) {
            mIdx++;
            // 当目标符号第N次出现的位置
            if (mIdx == n) {
                break;
            }
        }
        return slashMatcher.start();
    }

 

posted @ 2017-08-03 09:17  山水花草  阅读(941)  评论(0)    收藏  举报