【问题标题】:Program to Encrypt Text Depending on the Length of a Word根据单词长度加密文本的程序
【发布时间】:2016-12-20 19:55:32
【问题描述】:

我想制作一个根据文本长度加密文本的程序。例如,如果单词是“test”,那么因为“test”有 4 个字母,它会将单词中的每个字母移动到下一个字母的第 4 个。这将使“测试”变为“xiwx”。我已经完成了我的程序的一部分。就是这样:

public static void main(String[] args){
    string.toLowerCase();
    int charPos = 0;
    int length = 0;

    for(int i = 0; i < string.length(); i++){
        charPos = 0;
        length = 0;
        while(!(string.charAt(i) == ' ')){
            length = charPos;
            charPos++;
        }
        length--;
        for(int j = 0; j<=length; j++){
            char cha =string.charAt(i);

            //HERE IS WHERE THE CHAR ADDING WILL HAPPEN

        }
        i++;

    }

}//end

【问题讨论】:

  • 你可以做char shifted = cha + 3。需要小心从 Z 滚回 A。
  • 你有什么问题?
  • @Thilo 我该如何使用它?
  • 查看其他“凯撒密码”代码,例如stackoverflow.com/questions/30007467/caesar-cipher-java 可以看到,可以使用c + 4 “添加四个字母”。
  • 我知道你可以只做(字母)+长度。但是现在它将显示为该字母的 ascii 数字...

标签: java encryption char string-length


【解决方案1】:

有一种更简单的方法来实现这种类型的加密,只需使用一个循环。

加密:

String str = "test"; // normal string

String encryptedStr = ""; // start empty then add characters

for (char ch : str.toCharArray()) // loop through each character in str

    encryptedStr += (char) (ch + str.length()); // need to cast addition to char

System.out.println("Encrypted String: " + encryptedStr); // output encrypted string

所以想法是使用 length() 方法来获取字符串的长度,因为这就是您要添加到每个字符的内容。因为每个字符都有一个 ASCII 整数值,我们可以对它们执行数学运算(所以在这种情况下,将长度添加到每个字符)。然后,由于结果将是一个整数,我们必须在结果中添加一个 (char) 强制转换,以将其转换回一个字符。然后我们可以将此字符连接到空字符串。如果我们对原始字符串中的每个字符执行此操作(通过使用 for 循环并将字符串转换为 char 数组),我们最终将得到最后的加密字符串。

同样的想法也适用于解密:

String str = "xiwx"; // encrypted string

String decryptedStr = ""; // start empty then add characters

for (char ch : str.toCharArray()) // loop through each character in str

    decryptedStr += (char) (ch - str.length()); // need to cast subtraction to char

System.out.println("Decrypted String: " + decryptedStr); // output decrypted string

除了我们从每个字符中减去长度。

希望这有帮助:)

【讨论】:

  • 我知道你可以只做(字母)+长度。但是现在它将显示为该字母的 ascii 数字...
  • 是的,但如果其他人想知道它是如何工作的。
  • 我被禁止提问,因为我的票数很低
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-08
  • 1970-01-01
  • 1970-01-01
  • 2016-07-23
  • 2016-08-30
相关资源
最近更新 更多