我决定编写自己的 subString 方法,但是当我在我的测试驱动程序中对其进行测试时,我在我的 SubString 方法中收到一条错误消息。这是错误:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6
at java.lang.String.charAt(Unknown Source)
at unisa.util.StringImproved.subString(StringImproved.java:618)
这是我的子字符串的代码:
public String subString(int start, int end) {
//empty string to append the new string's characters to
String subString = "";
//creating a new string to store content to allow function
String s1 = new String(content);
//read each character in the string and append based on the index
for (int i=start; i<=end; i++){
subString += s1.charAt(i);
}
//convert string back to a char array
content = subString.toCharArray();
return subString;
}
错误是拿起线 subString += s1.charAt(i); 任何人都能够阐明我做错了什么?
PS。这不是为了分配,只是有点无聊,想自己重新创建 java 函数。
提前致谢!!
我已根据要求添加了我的测试方法!!
private int testSubString(String testID) {
int errorCount=0;
header(testID);
{
System.out.println("Test[getting substring from middle] ");
StringImproved str = new StringImproved("0123456789");
String result = str.subString(1,2);
errorCount+=handleResult(result,"1")?0:1;
}
{
System.out.println("Test[getting first characters] ");
StringImproved str = new StringImproved("0123456789");
String result = str.subString(0,2);
errorCount+=handleResult(result,"01")?0:1;
}
{
System.out.println("Test[getting last characters] ");
StringImproved str = new StringImproved("0123456789");
String result = str.subString(str.length()-3,str.length());
errorCount+=handleResult(result,"789")?0:1;
}
{
System.out.println("Test[out of range] ");
StringImproved str = new StringImproved("0123456789");
String result = str.subString(0,str.length()+1);
errorCount+=handleResult(result,null)?0:1;
}
{
System.out.println("Test[zero length source] ");
StringImproved str = new StringImproved("");
String result = str.subString(0,str.length()-1);
errorCount+=handleResult(result,null)?0:1;
}
return errorCount;
}