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