Skip to content

Instantly share code, notes, and snippets.

@fabiolimace
Last active July 25, 2020 18:32
Show Gist options
  • Save fabiolimace/8c181cc2c97dd34a755554ff3291699c to your computer and use it in GitHub Desktop.
Save fabiolimace/8c181cc2c97dd34a755554ff3291699c to your computer and use it in GitHub Desktop.
Replace chars of a String in Java, equivalent to bash 'tr' and perl 'tr///', aka, transliterate
package your.package.name;
/**
* Utility class that replaces chars of a String, aka, transliterate.
*
* It's equivalent to bash 'tr' and perl 'tr///'.
*
* @author: Fabio Lima 2020
*/
public class ReplaceChars {
public static String replace(String string, String from, String to) {
return new String(replace(string.toCharArray(), from.toCharArray(), to.toCharArray()));
}
public static char[] replace(char[] chars, char[] from, char[] to) {
char[] output = chars.clone();
for (int i = 0; i < output.length; i++) {
for (int j = 0; j < from.length; j++) {
if (output[i] == from[j]) {
output[i] = to[j];
break;
}
}
}
return output;
}
/**
* For tests!
*/
public static void main(String[] args) {
// Example from: https://en.wikipedia.org/wiki/Caesar_cipher
String string = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG";
String from = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String to = "XYZABCDEFGHIJKLMNOPQRSTUVW";
System.out.println();
System.out.println("Cesar cypher: " + string);
System.out.println("Result: " + ReplaceChars.replace(string, from, to));
}
}
/**
* OUTPUT
*
* Cesar cypher: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
*
* Result: QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD
*
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment