简体   繁体   中英

How to do a left Caesar shift in Java?

I've figured out how to shift a string right using this block of code:

for (int i = 0; i < phraseArray.length; i++) {
  phraseArray[i] = (char) ((phraseArray[i] + add - (int)'a') % 26 + (int)'a'); 
}

This allows me to loop a character near the end of the alphabet (such as 'z') to a character near the beginning (such as 'a') if the shift is too big. However, I can't seem to do a shift to the left and have a character near the beginning loop to a character near the end. Any ideas?

Since this a caesar shift and you know the number of letters in the alphabet used(I asume it is 26 letters), all you have to do is add 26, because -1 "equals" 25 in this case. And of course % the "add" variable to prevent making it bigger than 26. Below is Your program with small change that shows what I mean:

public static void main(String[] args){
    char[] phraseArray = {'a', 'b', 'c'};
    int add = -1;

    for (int i = 0; i < phraseArray.length; i++) {
        if(add>=0) {
            phraseArray[i] = (char) ((phraseArray[i] + add - (int) 'a') % 26 + (int) 'a');
        }else{
            phraseArray[i] = (char) ((phraseArray[i] + (26+(add%26)) - (int) 'a') % 26 + (int) 'a');
        }
        System.out.println(phraseArray[i]);
    }

    return;
}

If you want it to always be done to the left for should look like this:

for (int i = 0; i < phraseArray.length; i++) {
        phraseArray[i] = (char) ((phraseArray[i] + (26+(-add%26)) - (int)     'a') % 26 + (int) 'a');
    System.out.println(phraseArray[i]);
}

full main below:

public static void main(String[] args){
    int[] abc = {2, 4, 8, 3};
    char[] phraseArray = {'a', 'b', 'c'};
    int add = 1;

    for (int i = 0; i < phraseArray.length; i++) {
            phraseArray[i] = (char) ((phraseArray[i] + (26+(-add%26)) - (int) 'a') % 26 + (int) 'a');
        System.out.println(phraseArray[i]);
    }

    return;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM