如何移动数组中的每个 'nth' 个字符?

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

我正在尝试修改凯撒移位程序,使其不是移位数组中的每个字符,而是每隔 5 个字符移位一次。目前,可以将字符输入到文本区域中,然后将其转换为数组,并且每个字符都会按 shiftAmount(Key) 的值(如您所期望的那样)移动。 "abc" --by2--> "cde".

我尝试了 (int i=0; i<ptArray.length; i+=5),结果似乎每第 5 个字符(包括第 1 个)移动一次,但也只计算那些移动的字符,因此不显示数组中的任何其他字符。我可以对循环进行修改以实现此目的吗?理想情况下 "abcdefghij" 每第 5 个字母移动 2 将显示为 "abcdgfghil"

我正在尝试通过使用多整数密钥将每个字符同时移动不同的数量来制作更安全的密码。任何帮助将非常感激。

    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;

如果您仍想对每个字符进行操作,但只移动第五个字符,您可以将 for 循环更改为使用模数:

for(int i=0; i < ptArray.length; i++){
     if( i%5 == 0 ){
         // Shifting the array code.
     }
     // Other character counting code.
}

这就是您要达到的目的吗?

因此,您正在为消息中的某些字母制作 Vigenère chiper。最好加密所有字母并使用更长的密钥。

for(int i=0; i<ptArray.length; i+=5) 将遍历数组中的每 5 个字母。 (别忘了给变量赋值i)。

只使用一个数组,除非你想要一个只包含新字母的数组。覆盖第一个数组中的旧字母。

更新

有两种方法可以做到这一点

首先:遍历数组中的每第 5 个索引(0、4、9、14... 等等),并更改 原始 数组中的那个字母。

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

第二步:将所有值复制到一个新数组中,每5个元素改变一次。

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