-1

I'm trying to create a program that prints the text between two delimiters.

For example, in the string "superior sanguine bears" it returns an array of length 4 that contains "" "uperior" "anguine bear" "".

Below is my code. The issue I'm running into is that I'm getting a java.lang.ArrayIndexOutOfBoundsException: 23 at the line result[arrayLength] = s.substring(beginIndex, endIndex);

public static String[] explode(String s, char d)
{
    String[] result;
    int stringLength;
    int beginIndex, endIndex;
    beginIndex = 0;
    endIndex = 0;
    int arrayLength = 0;

    stringLength = s.length();//set stringLength equal to length of string s
    result = new String[stringLength];

    for(int i = 0; i < stringLength; i++)
    {
        if(s.charAt(i) == d)
        {
            if(i == 0)
            {
                result[arrayLength] = "";
                arrayLength++;
            }
            beginIndex = i+1;
            System.out.println("beginIndex" + beginIndex);
        }


        for(int j = i+1; j < stringLength; j++)
        {
            if((s.charAt(j) == d) || (j == stringLength-1))
                endIndex = j;

            if(beginIndex == endIndex)
            {
                result[arrayLength] = s.substring(beginIndex);
                arrayLength++;
            }
            else if(endIndex > beginIndex)
            {
                System.out.println(endIndex);
                result[arrayLength] = s.substring(beginIndex, endIndex);
                arrayLength++;

            }
        }
    }


    return result;
}

public static void main(String[] args)
{
    String s = "superior sanguine bears";
    char d = 's';
    String[] answer = explode(s, d);

    System.out.println(Arrays.toString(answer));
}
4

2 回答 2

1

您收到 ArrayIndexOutOfBoundsException,因为您要读取不存在的索引。数组索引从 0 开始,直到 n-1 元素。只需使用以下代码:

String string = "superior sanguine bears";
String[] parts = string.split("s", -1);
System.out.println(parts);

应该够好了。注意:我假设“s”是您的分隔符。

于 2013-09-11T04:06:22.960 回答
0

你可以这样做

    package code.java.test;


import java.util.ArrayList;
import java.util.List;

public class Main {
    public static List<String> explode(String s, char d)
    {
       List<String> ret = new ArrayList<String>();
       int beginIndex =0;
       int endIndex = 0;
       while((endIndex = s.indexOf(d, beginIndex)) != -1){
           ret.add(s.substring(beginIndex, endIndex).trim());
           beginIndex = endIndex+1;
       }
       ret.add(s.substring(beginIndex, s.length()));
       return ret;

    }

    public static void main(String[] args)
    {
        String s = "superior sanguine bears";
        char d = 's';
        List<String> answer = explode(s, d);

        System.out.println(answer.toString());
    }
}

O/P: [, 上级, anguine bear, ]

于 2013-09-11T04:36:51.930 回答