Write a program to encode and decode a string in java
To write a Java program that encodes and decodes a string, you can use a simple substitution cipher. In a substitution cipher, each character in the original string is replaced with a different character or symbol to produce the encoded string. To decode the string, you can simply apply the same substitution in reverse to get the original string back.
Here is an example of how you might write a Java program that uses a substitution cipher to encode and decode a string:
class Cipher {
public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
public static final String CIPHER = "zyxwvutsrqponmlkjihgfedcba";
public static String encode(String str) {
StringBuilder sb = new StringBuilder();
for (char c : str.toLowerCase().toCharArray()) {
int index = ALPHABET.indexOf(c);
if (index != -1) {
sb.append(CIPHER.charAt(index));
} else {
sb.append(c);
}
}
return sb.toString();
}
public static String decode(String str) {
StringBuilder sb = new StringBuilder();
for (char c : str.toLowerCase().toCharArray()) {
int index = CIPHER.indexOf(c);
if (index != -1) {
sb.append(ALPHABET.charAt(index));
} else {
sb.append(c);
}
}
return sb.toString();
}
}
0 Comments
if you are not getting it then ask i am glad to help