0

I am making a program to convert a message into a coded form of that message. I have done this with python, ut cannot find a similar method in java.

I tried similar commands, ut none worked.

  • Print the result of `str.maketrans("a","b")` it just produces a dictionary based on the ascii values of its inputs. This seems promising though if you don't want to roll it yourself https://blog.cskr.dev/posts/pythons-string-translations-for-java/ – JonSG Jan 27 '23 at 19:36
  • Is the way you are using the word "coded" the same as the word "encoded", like cryptographically encoded? – ControlAltDel Jan 27 '23 at 19:38
  • Does this answer your question? [Java, How to implement a Shift Cipher (Caesar Cipher)](https://stackoverflow.com/questions/19108737/java-how-to-implement-a-shift-cipher-caesar-cipher) – JonSG Jan 27 '23 at 19:39
  • @ControlAltDel Yes – Ethan Coleman Jan 27 '23 at 20:42
  • @JonSG not really... trying to have entire new thing not shift... – Ethan Coleman Jan 27 '23 at 20:43

2 Answers2

0

If you mean an alternative for using the maketrans() and translate() python functions, then you can achieve similar functionality in Java by using the replace() method from the String class.

String original = "abcdefg";
String replaced = original.replace('a', 'z');
System.out.println(replaced);

This would result in the output of "zbcdefg"

0

You can do it like this.

System.out.println(trans("this is a test", "tis", "xy"));
System.out.println(trans("Hello", "Heo", "Joy"));

prints

xhyx yx a xexx
Jolly

This works by simply by replacing the target character specified in the source string at location index with character in the dest string at the same location. If the destination string is shorter than the source string, then the remainder function is used to correct the index by wrapping around. Then the resultant string is returned.

public static String trans(String target, String source,String dest) {
    char[] chars = target.toCharArray();
    for(int i = 0; i < target.length(); i++) {
        int index = source.indexOf(chars[i]);
        if (index >= 0) {
            index %= dest.length();
            chars[i] = dest.charAt(index);
        }
    }
    return new String(chars);
    
}
WJS
  • 36,363
  • 4
  • 24
  • 39