您的位置:首页 > 其它

使用String类的indexOf()和subString方法犯了一个低级的错误

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

publicintindexOf(Stringstr,intfromIndex){ returnindexOf(value,offset,count, str.value,str.offset,str.count,fromIndex); } //source源字符,sourceOffset源偏移,sourceCount源长度 //target查找的字符... staticintindexOf(char[]source,intsourceOffset,intsourceCount, char[]target,inttargetOffset,inttargetCount, intfromIndex){ //如果fromIndex比源字符还长(从0算起),并且查找的字符长度为0,那就返回源字符的长度,否则返回-1 if(fromIndex>=sourceCount){ return(targetCount==0?sourceCount:-1); } if(fromIndex<0){ fromIndex=0; } //如果fromIndex比源字符短,查找的字符长度为0,直接返回fromIndex if(targetCount==0){ returnfromIndex; } //先取出第一个字符 charfirst=target[targetOffset]; intmax=sourceOffset+(sourceCount-targetCount); //循环每一个字符 for(inti=sourceOffset+fromIndex;i<=max;i++){ /*直到找到第一个字符*/ if(source[i]!=first){ while(++i<=max&&source[i]!=first); } /*找到第一个字符后,比较剩下的字符*/ if(i<=max){ intj=i+1; intend=j+targetCount-1; for(intk=targetOffset+1;j<end&&source[j]== target[k];j++,k++); if(j==end){ /*如果j能到end,那就说明找到整个字符串啦,返回偏移*/ returni-sourceOffset; } } } return-1; }


/**
*Returnsanewstringthatisasubstringofthisstring.The
*substringbeginsatthespecified<code>beginIndex</code>and
*extendstothecharacteratindex<code>endIndex-1</code>.
*Thusthelengthofthesubstringis<code>endIndex-beginIndex</code>.
*<p>
*Examples:
*<blockquote><pre>
*"hamburger".substring(4,8)returns"urge"
*"smiles".substring(1,5)returns"mile"
*</pre></blockquote>
*
*@parambeginIndexthebeginningindex,inclusive.
*@paramendIndextheendingindex,exclusive.
*@returnthespecifiedsubstring.
*@exceptionIndexOutOfBoundsExceptionifthe
*<code>beginIndex</code>isnegative,or
*<code>endIndex</code>islargerthanthelengthof
*this<code>String</code>object,or
*<code>beginIndex</code>islargerthan
*<code>endIndex</code>.
*/
publicStringsubstring(intbeginIndex,intendIndex){
if(beginIndex<0){
thrownewStringIndexOutOfBoundsException(beginIndex);
}
if(endIndex>count){
thrownewStringIndexOutOfBoundsException(endIndex);
}
if(beginIndex>endIndex){
thrownewStringIndexOutOfBoundsException(endIndex-beginIndex);
}
return((beginIndex==0)&&(endIndex==count))?this:
newString(offset+beginIndex,endIndex-beginIndex,value);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  indexOf substring
相关文章推荐