Dale
Dale

Reputation: 599

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?

Upvotes: 3

Views: 13064

Answers (4)

Op De Cirkel
Op De Cirkel

Reputation: 29473

String.substring(begining, endIndexExclusive) when a=1, beginIndex=1, endIndexExclusive=1 =>
sTemp == "" =>
toCharArray() returns empty array => [0] indexOutOfBounds

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533510

When you use the debugger, you can see that the first time round the loop, you get one character and the second time you get no characters.

That is because String.substring(int start, int end) takes the end, not the length.

BTW: You can just write

int[] sbox = new int[256];
String inputString = "Thisisanexample";
for(int i = 0; i < sbox.length; i++)
    sbox[i] = inputString.charAt(i % inputString.length());

Upvotes: 0

mark-cs
mark-cs

Reputation: 4707

If in doubt check the javadoc this shows you that substring() does not do what you think it does...

Upvotes: 0

x4u
x4u

Reputation: 14077

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

Upvotes: 5

Related Questions