在下面的代码中,我试图基于开始和结束索引来做子字符串,但是在字符串的末尾。系统抛出ArrayIndexOutOfBoundsException
。请让我知道如何解决此问题。
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int initlength = 20;
int start = 0;
String s = "Some people confuse acceptance with apathy, but there's all "+
"the difference in the world";
int total=(int)Math.ceil((double)s.length()/(double)initlength);
for (int i = 0; i < total; i++) {
System.out.println("s length" + s.substring(start, initlength));
start = initlength + 1;
initlength = initlength + initlength;
}
}
问候,
混沌
最佳答案
逐步调试代码:
第一次变量start=0;initlength=0;s="Some people confuse acceptance with apathy, but there's all the difference in the world";total = 5.
s.length()/initlength = 4.
第一个子字符串为0到20。start = 21
和initlenght = 40
第二次循环s.length()/initlength = 2
子串从21到40。start = 41
和initlength = 80
。
第三次循环。s.length()/initlength = 1
和i
等于2,因此循环将中断并且程序执行将结束。
根据您的编辑。现在它将循环5次。并且在第三次start = 81
和initlength = 160
超出字符串范围之后。一直以来total = 5
。
如果您希望获得剩余部分,请尝试以下操作:
int initlength = 20;
int start = 0;
String s = "Some people confuse acceptance with apathy, but there's all "
+ "the difference in the world";
int total = (int) Math.ceil((double) s.length() / (double) initlength);
for (int i = 0; i < total; i++) {
if(initlength<s.length()){
System.out.println("s length" + s.substring(start, initlength));
start = initlength + 1;
initlength = initlength + initlength;
} else {
initlength = s.length();
System.out.println("s length" + s.substring(start, initlength));
break;
}
}
输出:-
s lengthSome people confuse
s lengthcceptance with apat
s lengthy, but there's all the difference in th
s length world