简体   繁体   中英

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. ' B ' in the Substitution maps to ' Y 'in the English Alphabet hence why it is the second letter and so fourth...

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

input =           "XVSHJQEMZKTUIGAPOYLRWDCFBN"
Expected output = "OYWVGXNDMEJSHZQPFTCKLBUARI"
My output =       "XVSHJQEMZKTUIGAPOYLRWDCFBN"
  1. For input "XVSHJQEMZKTUIGAPOYLRWDCFBN" and the same substitution "XVSHJQEMZKTUIGAPOYLRWDCFBN" a "normal" alphabet should be returned.

  2. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM