[英]Substituting characters from alphabet array with input string
I am creating a method that when given a substitution code it returns the substitution code which can be used to decode any message我正在创建一种方法,当给定替换代码时,它会返回可用于解码任何消息的替换代码
An example of what I mean is found below下面是我的意思的一个例子
English Alphabet = ABCDEFGHIJKLMNOPQRSTUVWXYZ
substitution = XVSHJQEMZKTUIGAPOYLRWDCFBN
Output I want = OYWVGXNDMEJSHZQPFTCKLBUARI
As you can see above ' A ' in the Substitution maps to ' O ' on the English Alphabet hence why in the output ' O ' is the first letter.正如您在上面看到的,替换中的“ A ”映射到英文字母表上的“ O ”,因此在output中,“ O ”是第一个字母。 ' B ' in the Substitution maps to ' Y 'in the English Alphabet hence why it is the second letter and so fourth...
替换中的“ B ”映射到英文字母表中的“ Y ”,因此它是第二个字母,所以是第四个......
The code I created我创建的代码
public static String getRev(String s)
{
char normalChar[]
= { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
String revString = "";
for (int i = 0; i < s.length(); i++) {
for (int j = 0; j < 26; j++) {
if (s.indexOf(i) == normalChar[j])
{
revString += normalChar[j];
break;
}
}
}
return revString;
}
l l
input = "XVSHJQEMZKTUIGAPOYLRWDCFBN"
Expected output = "OYWVGXNDMEJSHZQPFTCKLBUARI"
My output = "XVSHJQEMZKTUIGAPOYLRWDCFBN"
For input "XVSHJQEMZKTUIGAPOYLRWDCFBN"
and the same substitution "XVSHJQEMZKTUIGAPOYLRWDCFBN"
a "normal" alphabet should be returned.对于输入
"XVSHJQEMZKTUIGAPOYLRWDCFBN"
和相同的替换"XVSHJQEMZKTUIGAPOYLRWDCFBN"
,应返回“正常”字母表。
To get "OYWVGXNDMEJSHZQPFTCKLBUARI"
for the provided substitution and normal alphabet as input, an index of char from the input
is located in the substitution
and this index is used to find a char in normal alphabet:要为提供的替换和普通字母表获取
"OYWVGXNDMEJSHZQPFTCKLBUARI"
作为输入, input
中的 char 索引位于substitution
中,并且该索引用于在普通字母表中查找 char:
public static String getRev(String s) {
String normal = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String substitution = "XVSHJQEMZKTUIGAPOYLRWDCFBN";
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
int index = substitution.indexOf(c);
if (index >-1) {
sb.append(normal.charAt(index));
}
}
return sb.toString();
}
Tests:测试:
System.out.println(getRev("ABCDEFGHIJKLMNOPQRSTUVWXYZ")); // OYWVGXNDMEJSHZQPFTCKLBUARI
System.out.println(getRev("XVSHJQEMZKTUIGAPOYLRWDCFBN")); // ABCDEFGHIJKLMNOPQRSTUVWXYZ
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.