I am implementing an monoalphabetic substitution algorithm. Keys and values are stored in the HashMap, and as a parameter of the input string using a variable of StringBuffer class type:
public class Mono {
private StringBuffer source;
private Map<String, String> alphabet;
public Mono(String source) {
this.source = new StringBuffer(source);
alphabet = new HashMap<>();
alphabet.put("a", "f");
alphabet.put( //... etc.
}
public StringBuffer startEncrypt() {
for (int i = 0; i < source.length(); i++) {
for (Map.Entry entry : alphabet.entrySet()) {
if (entry.getKey().toString().equals(source.charAt(i))) {
source.setCharAt(i, entry.getValue().toString());
}
}
}
return source;
}
}
I encountered a problem converting string to char here: source.setCharAt(i, entry.getValue().toString());
So, my question is how to do it? Or is there another, better way of replacing characters?
Thanks.
You can just use charAt(0)
to get the first character of a string... just like you're already doing for your key. Note that if you use a parameterized Map.Entry
instead of the raw type, you won't need the toString
call either:
for (Map.Entry<String, String> entry : alphabet.entrySet()) {
// TODO: Should this be source.charAt(i)?
if (entry.getKey().equals(source.charAt(0))) {
source.setCharAt(i, entry.getValue().charAt(0));
}
}
That said, if all your strings are really just a single character, why don't you use a Map<Character, Character>
? Additionally, iterating over all the entries in the map is inefficient and almost certainly not what you want to do. I suspect you actually want something like:
private final Map<Character, Character> mappings;
public String substitute(String input) {
char[] chars = input.toCharArray();
for (int i = 0; < chars.length; i++) {
Character sub = mapping.get(chars[i]);
if (sub != null) {
chars[i] = sub;
}
}
return new String(chars);
}
See more on this question at Stackoverflow