Search code examples
javavigenere

Fill Array With repeated String - JAVA


I'm implementing a Vigenere Ciphering and lets say I have a String called key with value for example "KEY"

and I want to fill array of char with that string for size of plainText

For example I have a plain Text "JAVA IS BEST" the char Array depending on plaintext will be:

input: ['J','A','V','A',' ','I','S',' ','B','E','S','T']

output: ['K','E','Y','K',' ','E','Y',' ','K','E','Y','K']

How I can make the same output array above?


Solution

  • You can do this by looping over the original char[], and if the given character is not a space, then copy the corresponding letter of the key to the matching index of the char[] that you will return. You can find the matching letter of the key by using the % operator. The problem you encountered is that if the character at i is equal to a space, i will be incremented still and you will skip a letter for key. To fix this you can add an extra counter variable:

    public static char[] foo(char[] arr) {
        String key = "KEY";
        char[] copy = new char[arr.length];
        for(int i = 0, index = 0; i < arr.length; i++) {
            if(arr[i] != ' ') {
                copy[i] = key.charAt(index++ % key.length());
            } else {
                copy[i] = ' ';
            }
        }
        return copy;
    }
    

    Output:

    ['K','E','Y','K',' ','E','Y',' ','K','E','Y','K']