今天在公司開發,在使用String類的字符串操做函數的時候犯了一個比較低級的錯誤。緣由是本身對substring()方法以及indexOf()方法的使用瞭解的不夠深刻。
錯誤的代碼以下:String frpName = frpName.substring(0, frpName.indexOf("("));用處是:當字符串後面包含(),就將()去掉。由於少判斷了indexOf("(")等於-1的狀況,因此程序編譯沒有出錯,卻在運行的時候致使系統出現了問題。
兩個函數的源代碼以下:
java
public int indexOf(String str, int fromIndex) { return indexOf(value, offset, count, str.value, str.offset, str.count, fromIndex); } //source源字符,sourceOffset源偏移,sourceCount源長度 //target查找的字符 ... static int indexOf(char[] source, int sourceOffset, int sourceCount, char[] target, int targetOffset, int targetCount, int fromIndex) { //若是fromIndex比源字符還長(從0算起),而且查找的字符長度爲0,那就返回源字符的長度,不然返回-1 if (fromIndex >= sourceCount) { return (targetCount == 0 ? sourceCount : -1); } if (fromIndex < 0) { fromIndex = 0; } //若是fromIndex比源字符短,查找的字符長度爲0,直接返回fromIndex if (targetCount == 0) { return fromIndex; } //先取出第一個字符 char first = target[targetOffset]; int max = sourceOffset + (sourceCount - targetCount); //循環每個字符 for (int i = sourceOffset + fromIndex; i <= max; i++) { /* 直到找到第一個字符 */ if (source[i] != first) { while (++i <= max && source[i] != first); } /* 找到第一個字符後,比較剩下的字符 */ if (i <= max) { int j = i + 1; int end = j + targetCount - 1; for (int k = targetOffset + 1; j < end && source[j] == target[k]; j++, k++); if (j == end) { /* 若是j能到end,那就說明找到整個字符串啦,返回偏移 */ return i - sourceOffset; } } } return -1; }
/** * Returns a new string that is a substring of this string. The * substring begins at the specified <code>beginIndex</code> and * extends to the character at index <code>endIndex - 1</code>. * Thus the length of the substring is <code>endIndex-beginIndex</code>. * <p> * Examples: * <blockquote><pre> * "hamburger".substring(4, 8) returns "urge" * "smiles".substring(1, 5) returns "mile" * </pre></blockquote> * * @param beginIndex the beginning index, inclusive. * @param endIndex the ending index, exclusive. * @return the specified substring. * @exception IndexOutOfBoundsException if the * <code>beginIndex</code> is negative, or * <code>endIndex</code> is larger than the length of * this <code>String</code> object, or * <code>beginIndex</code> is larger than * <code>endIndex</code>. */ public String substring(int beginIndex, int endIndex) { if (beginIndex < 0) { throw new StringIndexOutOfBoundsException(beginIndex); } if (endIndex > count) { throw new StringIndexOutOfBoundsException(endIndex); } if (beginIndex > endIndex) { throw new StringIndexOutOfBoundsException(endIndex - beginIndex); } return ((beginIndex == 0) && (endIndex == count)) ? this : new String(offset + beginIndex, endIndex - beginIndex, value); }