简体   繁体   English

Java中字符串的简单加密

[英]Simple encryption of a String in Java

I want to write a program which will take a String and add 2 to every character of the String this was quite simple Here is my code. 我想编写一个程序,该程序将使用一个String并将2添加到String的每个字符中,这很简单这是我的代码。 Example:- 例:-

String str="ZAP YES";
nstr="BCR AGU" //note Z=B and Y=A

String str=sc.nextLine();
String nstr=""    
for(int i=0;i<str.length();i++)
    {
        char ch=sc.charAt(i);
        if(ch!=' ')
        {
            if(ch=='Z')
                ch='B';
            else if(ch=='Y')
                ch='A';
            else
                ch=ch+2;
        }
        nstr=nstr+ch;
    }

Now I want to increase every character by n(instead of 2) and this really I could not solve. 现在我想将每个字符增加n(而不是2),而这确实是我无法解决的。

I might think of using n%26 ,and use a loop for conditions but I was not able to solve it how to implement that. 我可能会考虑使用n%26,并为条件使用循环,但是我无法解决如何实现该问题。

You have the right idea with using % 26 . 使用% 26是正确的主意。 The missing piece is that your range isn't zero-based. 缺少的部分是您的范围不是从零开始的。 You can simulate a zero-based range by subtracting 'A' (i..e, treating 'A' as 0, 'B' as 1, etc), and then readding it: 您可以通过减去“ A”(即将“ A”视为0,将“ B”视为1,以此类推)来模拟从零开始的范围,然后读取它:

for (int i = 0; i < str.length(); i++) {
    char ch = str.charAt(i);
    if (ch != ' ') {
        ch = (char)((ch - 'A' + n) % 26 + 'A');
    }

    nstr += ch;
}

You have to: 你必须:

  1. Take your character and remap it to a 0-26 index 以您的角色并将其重新映射到0-26索引
  2. Add your increment to that index 将您的增量添加到该索引
  3. Apply a 26 mod to the result 将26 mod应用于结果
  4. Remap the index back again to ASCII 重新将索引重新映射回ASCII

Example: 例:

public static char increment(char c, int n) {
   return (char) (((c - 'A') + n) % 26 + 'A');
}

public static void main(String[] args) {
  System.out.println(increment('Z', 1)); // returns 'A'
  System.out.println(increment('Z', 2)); // returns 'B'
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM