简体   繁体   中英

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. 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.

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.

You have the right idea with using % 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:

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
  2. Add your increment to that index
  3. Apply a 26 mod to the result
  4. Remap the index back again to 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'
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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