Search code examples
javaarraysloopsencryptioncaesar-cipher

How to shift every 'nth' character in an array?


I'm trying to modify a caesar shift program to shift not every character in an array but say every 5th character. Currently, characters can be input into a textarea which is then converted to an array and every character is shifted by whatever the shiftAmount(Key) is(as you'd expect). "abc" --by2--> "cde".

I tried (int i=0; i<ptArray.length; i+=5) which results in shifting every 5th character(including the 1st) it seems but also only counting those characters shifted thus not displaying any other characters in the array. Is there a modification I can make to the loop to achieve this? Ideally "abcdefghij" with every 5th letter shifted by 2 would display as "abcdgfghil"

I'm trying to make a more secure cipher by shifting each character simultaneously by a different amount with a multi-integer key. Any help would be much appreciated.

    public String shiftCipher (String p, int s) { //plaintext, shiftAmount
        //convert the input/plain string to an array of characters 
        char[] ptArray = p.toCharArray();
        //create array of characters to hold output/cipher string 
        char[] ctArray = new char[ptArray.length];

      //shift and put result in the ciphertext array
        for (int i=0; i<ptArray.length; i++) {
        int ascii = (int)ptArray[i];
        ascii = (ascii - 32 + s)%95 + 32;
        ctArray[i] = (char)ascii;
        }

          //convert ciphertext array to string
            String c = new String(ctArray);

            return c;

Solution

  • So you are making a Vigenère chiper for only some letters in the the message. Better to encrypt all letters and use a longer key.

    for(int i=0; i<ptArray.length; i+=5) will step through every 5th letter in the array. (Don't forgett the assignment to the variable i).

    Use only one array, unless you want an array with only the new letters. Overwrite the old lettets i the first array.

    Update

    There are two ways you can do this

    First: Loop through every 5th index in the array (0,4,9,14... and so on), and change that letter in the original array.

    for(int i=0; i < myArray.length; i+=5 ){
        myArray[i] = ...what to change to here..
    }
    

    Second: Copy all the values into a new array, and change every 5th element.

    char[] newArray = new char[oldArray.length];
        for(int i = 0; i < oldArray.length; i++) {
            if(i % 5 == 0) {  //Every 5th element
                newArray[i] = ...what to change to here...;
            } else {
                newArray[i] = oldArray[i];
                   }
    }