String 部分方法剖析
阿新 • • 發佈:2018-12-11
@Date:2018年08月13日16:55:06
- split
將輸入字串斷開成字串物件陣列,斷開邊界由正則表示式確定
- 替換操作
replace/replaceAll/appendReplacement 通過正則表示式來替換結果
- compareTo(String anotherString)
基於每個字元的unicode編碼值,比較兩個字串的字典順序。小於零則
public int compareTo(String anotherString) { int len1 = value.length; int len2 = anotherString.value.length; int lim = Math.min(len1, len2); char v1[] = value; char v2[] = anotherString.value; int k = 0; while (k < lim) { char c1 = v1[k]; char c2 = v2[k]; if (c1 != c2) { return c1 - c2; } k++; } return len1 - len2; }
- startsWith(String prefix, int toffset)
通過while迴圈判斷當前字串是否是在指定偏移量以指定字首開頭
public boolean startsWith(String prefix, int toffset) { char ta[] = value; int to = toffset; char pa[] = prefix.value; int po = 0; int pc = prefix.value.length; // Note: toffset might be near -1>>>1. if ((toffset < 0) || (toffset > value.length - pc)) { return false; } while (--pc >= 0) { if (ta[to++] != pa[po++]) { return false; } } return true; }
- indexOf
得到指定字串從指定索引開始哪個索引值
- subString(int beginIndex , int endIndex)
返回一個字串,該字串是此字串的子字串。 子字串從指定的beginIndex開始,並擴充套件到索引endIndex - 1處的字元. eg:String name = “zhuxiaolei” ; name = name.subString(4,8) = “iaol”;
public String substring(int beginIndex, int endIndex) { if (beginIndex < 0) { throw new StringIndexOutOfBoundsException(beginIndex); } if (endIndex > value.length) { throw new StringIndexOutOfBoundsException(endIndex); } int subLen = endIndex - beginIndex; if (subLen < 0) { throw new StringIndexOutOfBoundsException(subLen); } return ((beginIndex == 0) && (endIndex == value.length)) ? this : new String(value, beginIndex, subLen); }