Java String.substring returning empty string

I’m trying to run the following code

int[] sbox = new int[256];
String inputString = "Thisisanexample";
String sTemp;
char cTmp;
int intLength = inputString.length();

for (a = 0; a <= 255; a++)
{
    sTemp = inputString.substring(a % intLength, 1);
    ctmp = sTemp.toCharArray()[0];
    sbox[a] = (int)ctmp;
}

Every time i run the code I get a java.lang.ArrayIndexOutOfBoundsException when the counter variable = 1. Checking the code in the debugger, it appears the substring is returning an empty string when it should be returning the second character in the inputString.

Can anyone advise why this would be the case?

Answer

String.substring() expects a start and a end index, not the length. So you need to add the length to the start index:

for (a = 0; a <= 255; a++)
{
    int index = a % intLength;
    sTemp = inputString.substring( index, index + 1 );
    ctmp = sTemp.toCharArray()[0];
    sbox[a] = (int)ctmp;
}

You can also avoid the creation of sub strings in this case. This would give you the same results:

for (a = 0; a <= 255; a++)
{
    ctmp = inputString.charAt(a % intLength);
    sbox[a] = ctmp;
}

Leave a Reply

Your email address will not be published. Required fields are marked *