-
Notifications
You must be signed in to change notification settings - Fork 0
/
SubstitutionCipher.java
49 lines (48 loc) · 1.22 KB
/
SubstitutionCipher.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
Author: Mark Estep
Date: 1/5/22
Edited:
**/
public class SubstitutionCipher implements Cipherable{
private String key;
public SubstitutionCipher(String k){
key = k;
}
public String encode(String in){
String upper = in.toUpperCase();
String ans = "";
for(int i = 0; i < in.length(); i++){
char upperCh= upper.charAt(i);
if(Character.isLetter(upperCh)){
int index = upperCh - 'A';
char letter = key.charAt(index);
if(Character.isLowerCase(in.charAt(i))){
letter = Character.toLowerCase(letter);
}
ans += letter;
}else{
ans += upperCh;
}
}
return ans;
}
//"QWERTYUIOPASDFGHJKLZXCVBNM"
public String decode(String in){
String upper = in.toUpperCase();
String ans = "";
for(int i = 0; i < in.length(); i++){
char upperCh= upper.charAt(i);
if(Character.isLetter(upperCh)){
int index = key.indexOf(upperCh);//upperCh - 'A';
char letter = (char)(index + 'A');//key.charAt(index);
if(Character.isLowerCase(in.charAt(i))){
letter = Character.toLowerCase(letter);
}
ans += letter;
}else{
ans += upperCh;
}
}
return ans;
}
}