Write a program to encode and decode a string in java

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();

  }

}


To use this program, you can call the encode and decode methods as follows:

String original = "Hello, World!";
String encoded = Cipher.encode(original);
String decoded = Cipher.decode(encoded);

System.out.println("Original: " + original);
System.out.println("Encoded: " + encoded);
System.out.println("Decoded: " + decoded);

This will output the following:

Original: Hello, World!
Encoded: svvfl, dliow!
Decoded: hello, world!

Post a Comment

0 Comments