数组中子串的问题

时间:2013-09-11 04:02:40

标签: java

我正在尝试创建一个在两个分隔符之间打印文本的程序。

例如,在字符串"superior sanguine bears"中,它返回一个长度为4的数组,其中包含"" "uperior" "anguine bear" ""

以下是我的代码。我遇到的问题是我在第result[arrayLength] = s.substring(beginIndex, endIndex);行获得了一个java.lang.ArrayIndexOutOfBoundsException:23

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));
}

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分: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: [,uperior,anguine bear,]