ethanqt
ethanqt

Reputation: 63

Negative string index

I am doing some kind of cipher in Java for schools homework. The task is to change the value of a certian char to a new one with a specific offset which is given by the user and has a range from negative numbers to positive numbers (alphabet).

Now I have a problem with negative offsets. I have created a String with the Alphabet which helps to find the new char. For example: With the offset of 7 I got this: encrypt(“TEST”) = “ALZA”. So my code grabs the index of the string value and searches with this index in the alphabet string for the new char. Anyway when I now have the char 'E' and a negative index i.e '-7' it will return the value of -3 for the new index of the new char (I hope that makes sense). Since there is no char on index '-3' I get an error.

So how can I access to the end of the string instead of going more and more into negative index numbers ?

Upvotes: 2

Views: 1698

Answers (3)

Konstantin Pribluda
Konstantin Pribluda

Reputation: 12367

If you can constrain shift values to be positive, you can use remainder operator:

int newIndex = (index + shift) % 26

If there are negatives to be expected:

int newIndex = Math.floorMod(inndex + shift, 26) would do the trick

Actually you need mathematical modulo, but % operator is not quite that

Upvotes: 0

Bohemian
Bohemian

Reputation: 425033

Add 26 then mod 26:

i = (i + 26) % 26;

This always works for indexes down to -26. If that's not enough, just add some zeroes:

i = (i + 26000000) % 26;

Upvotes: 3

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521239

Your general problem appears to be that letters are represented by only 26 indices, but the actual index variable you use might be greater than 26, or even less than zero (negative). One way to handle this problem is to use the mod operator to safely wrap your index around to always point to a range containing a valid letter.

Here is logic which can do that:

if (index < 0) {
    index = (index % 26) + 26;
}
else {
    index = index % 26;
}

Assuming the letter E is position 5 and you have a reassignment of -7, this would mean that the new index would be -2. This new position can be mapped using the above logic as follows, where index = -2 in this case:

5 - 7 = -2
(-2 % 26) + 26
-2 + 26
24

And character in position 24 is the letter X.

Upvotes: 2

Related Questions