java获取字符串指定位置的字符_查找子字符串在字符串中的位置
有时会遇到从一个大的字符串提取一个子字符串的情况。
public static void main(String[] args) { Test t = new Test(); String str ="xmlns:etc=\"http://www.wps.cn/officeDocument/2017/etCustomData\"><sheetPr codeName=\"Sheet7\"><tabColor theme=\"5\" tint=\"0.599993896298105\"/><pageSetUpPr fitToPage=\"1\"/></sheetPr><dimension ref=\"A1:J29\"/><sheetViews><sheetView showGridLines=\"0\" zoomScale=\"110\" zoomScaleNormal=\"110\""; String startStr ="dimension ref=\"A1:"; String endStr ="\"/><sheetViews>"; int start = t.getKMPIndex(str, startStr); int end = t.getKMPIndex(str, endStr); String sub = str.substring(start+15, end); System.out.println(sub); } public int getKMPIndex(String string,String substring){ int i = 0; int j = 0; int[] nextval = getNextVal(substring); char[] stringCharArray = string.toCharArray(); char[] substringCahrArray = substring.toCharArray(); int stringlength = string.length() ; int substringlength = substring.length(); while (i < stringlength && j < substringlength){ if(j == -1 || stringCharArray[i] == substringCahrArray[j]){ i++; j++; }else { j = nextval[j]; } } if( j >= substringlength){ return i - substringlength; }else { return -1; } } private int[] getNextVal(String str){ int length = str.length(); int[] nextval = new int[length]; char[] strchar = str.toCharArray(); int j= 0; int k = -1; nextval[0] = -1; while (j < length-1){ if(k== -1 || strchar[j] == strchar[k] ){ j++; k++; if(strchar[j] != strchar[k]){ nextval[j] = k; }else { nextval[j] = nextval[k]; } }else { k = nextval[k]; } } return nextval; }