带循环的子串

时间:2011-05-13 11:59:26

标签: java string exception substring

在下面的代码中,我试图根据开始和结束索引来做子串,但是在字符串的末尾。系统正在抛出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;
            }
    }

此致

chaitu

2 个答案:

答案 0 :(得分:1)

逐步调试代码:

  1. 第一次变量

    start=0; initlength=0; s="Some people confuse acceptance with apathy, but there's all the difference in the world"; total = 5.

  2. s.length()/initlength = 4.

  3. 第一个子字符串将是0到20。
  4. start = 21initlenght = 40
  5. 第二次循环
  6. s.length()/initlength = 2
  7. 子串从21到40。
  8. start = 41initlength = 80
  9. 第三次循环。
  10. s.length()/initlength = 1i等于2因此循环将中断,程序执行将完成。

  11. 根据您的修改。现在它将循环5次。在第3次start = 81initlength = 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
    

答案 1 :(得分:0)

initlength是不是会越来越大,直到超过字符串的末尾?