1. 程式人生 > >java獲取某個字元在一個字串中出現的下標(從0開始)

java獲取某個字元在一個字串中出現的下標(從0開始)

<span style="font-size:18px;"><strong>獲取字元s在字串url中第i次出現的下標(從0開始)</strong></span>
/**
	 * @param url,s,i
	 * @return int
	 * @author shuws
	 */
	public static int getCharacterPosition(String url,String s,int i){
	    //這裡是獲取"/"符號的位置	lastindexof從字串末尾開始檢索,檢索到子字元
	    Matcher slashMatcher = Pattern.compile(s).matcher(url);
	    int mIdx = 0;
	    while(slashMatcher.find()) {
	       mIdx++;
	       //當"/"符號第i次出現的位置
	       if(mIdx == i){
	          break;
	       }
	    }
	    return slashMatcher.start();
	}