Encryption of String using Java. Write a program to encrypt the given string. Let “Old” be a string, its encrypted form would be “Ple”. Let us see the rules to encrypt the string.
String Encryption in Java using First Approach
Rules to Encrypt String
- Replace the characters at odd positions with the next character in the alphabet.
- Leave the characters at even positions unchanged.
- If an odd position character is ‘z’ replace it by ‘a’.
- Assume the first character in the string is at position 1.
Input and Output Format
- Input is an original string.
- The output is an encrypted string.
Sample Input 1:
curiosity
Sample Output 1:
dusipsjtz
Sample Input 2:
zzzz
Sample Output 2:
Azaz
String Encryption in Java
Following are the steps to perform string encryption in Java:
- Input a string.
- Pass the string to stringFormatting() method.
- Inside the method, Create a string buffer with no character in it.
- Iterate over the string and perform the following operation:
- Retrieve each character from the ith position, and check if the character is at an odd position, then add 1 to its ASCII value and append it to the string buffer. Else, just append it without changing.
- If the user input is ‘z’, then just subtract 25 from the ASCII value and append it to the string buffer.
- At last, just return the string.
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s1 = sc.nextLine(); System.out.println(stringFormatting(s1)); } public static String stringFormatting(String s1) { StringBuffer sb=new StringBuffer(); for(int i=0;i<s1.length();i++){ char c=s1.charAt(i); if(i%2==0){ if(c==122) c=(char) (c-25); else{ c=(char) (c+1);} sb.append(c);} else sb.append(c);} return sb.toString(); } }
Output
String Encryption in Java using Second Approach
Here, we will encrypt the character with the next two characters. Like for example, if a user enters the string “OLD” then the encrypted form would be “QNF”.
Input and Output Format
- Input is an original string.
- The output is an encrypted string.
Sample Input 1:
old
Sample Output 1:
qnf
Sample Input 2:
dcshbch2651561
Sample Output 2:
feujdej4873783
Program to encrypt a string in Java
Following are the steps to perform string encryption in Java:
- Input a string.
- Pass the string to encryptString() method.
- Inside the method, convert the string to a character array.
- Iterate over an array, add 2 to each character and print them.
package com.date; import java.util.Scanner; public class Practice { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String str = scanner.nextLine(); encryptString(str); } private static void encryptString(String str) { char c[] =str.toCharArray(); for(char c1 : c){ c1 = (char) (c1 + 2); System.out.print(c1); } } }
Output
Thus, in this way, you can encrypt the string based on the above approaches.