我正在尝试修改一个凯撒班次计划,不是要移动数组中的每个字符,而是要说每5个字符。目前,字符可以输入到textarea中,然后转换为数组,每个字符都按shiftAmount(Key)移动(正如您所期望的那样)。 “abc” - by2 - > “CDE”。
我尝试(int i=0; i<ptArray.length; i+=5)
导致每隔5个字符(包括第1个字符)移位,但也只计算那些移位的字符,从而不显示数组中的任何其他字符。我可以对循环进行修改以实现此目的吗?理想情况下,每隔5个字母移动2次的“abcdefghij”将显示为“abcd g fghi l ”
我正在尝试通过使用多整数键将每个字符同时移动不同的数量来制作更安全的密码。任何帮助将非常感激。
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;
答案 0 :(得分:2)
因此,您只为信息中的某些字母制作Vigenèrechiper。最好加密所有字母并使用更长的密钥。
for(int i=0; i<ptArray.length; i+=5)
将遍历数组中的每个第5个字母。 (不要忘记对变量i
)的赋值。
除非您想要一个只包含新字母的数组,否则只使用一个数组。在第一个数组中覆盖旧的lettets。
<强>更新强>
有两种方法可以做到这一点
首先:循环遍历数组中的每个第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];
}
}
答案 1 :(得分:1)
如果您仍想对每个角色进行操作,但只移动第五个角色,您可以更改for循环以使用模数:
for(int i=0; i < ptArray.length; i++){
if( i%5 == 0 ){
// Shifting the array code.
}
// Other character counting code.
}
这是你想要的吗?