今天在公司开发,在使用String类的字符串操作函数的时候犯了一个比较低级的错误。原因是自己对substring()方法以及indexOf()方法的使用了解的不够深入。
错误的代码如下:String frpName = frpName.substring(0, frpName.indexOf("("));用处是:当字符串后面包含(),就将()去掉。因为少判断了indexOf("(")等于-1的情况,所以程序编译没有出错,却在运行的时候导致系统出现了问题。
两个函数的源代码如下:
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);
}