1. 程式人生 > >java獲取字串中第N次出現特定字元的位置

java獲取字串中第N次出現特定字元的位置

/**
	 * 讀取字串第i次出現特定符號的位置
	 * @param string
	 * @param i
	 * @return
	 */
	public static int getCharacterPosition(String string ,int i,String character){
	    //這裡是獲取"/"符號的位置
	   // Matcher slashMatcher = Pattern.compile("/").matcher(string);
		 Matcher slashMatcher = Pattern.compile(character).matcher(string);
	    int mIdx = 0;
	    while(slashMatcher.find()) {
	       mIdx++;
	       //當"/"符號第三次出現的位置
	       if(mIdx == i){
	          break;
	       }
	    }
	    return slashMatcher.start();
	 }