用自定义字母替换字符串中的字符

时间:2018-12-11 17:48:17

标签: java

我已经编写了这段代码,用自定义提供的字母替换字符串中的字符:

//Replaces characters in string with custom alphabet.
public static String getStringWithCustomAlphabet(String string, String customAlphabet){
    String shiftedString = "";

    //Loop through every character in @plainText
    for (int i = 0; i < string.length(); i++) {

        //Store current character of loop in @charToAdd
        char charToAdd = string.charAt(i);

        int index = getAlphabet().indexOf(charToAdd);

        //If index is valid
        if (index != -1) charToAdd = customAlphabet.charAt(index);

        //Add the character to @cipherText
        shiftedString += charToAdd;
    }

    return shiftedString;
}

public static String getAlphabet() {
    return "abcdefghijklmnopqrstuvwxyz ";
}

此代码有效。但是,我希望不仅可以使用字符串字母,而且可以使用整数字母。因此,例如:

int[] numberArray {0,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};
getStringWithCustomAlphabet("abcxyz", numberArray); //Should return 0,1,2,23,24,25

也许有一些方法可以简化此代码而不使用for循环?

2 个答案:

答案 0 :(得分:0)

对于小写字母,请使用此:

String str = "abcdef";
char[] ch  = str.toCharArray();
for (char c : ch) {
   int temp = (int) c;
   int temp_integer = 96; //for lower case
   if (temp <= 122 & temp >= 97)
      System.out.print(temp-temp_integer);
}
  

输出将为-:123456

大写:

String str = "DEFGHI";
char[] ch  = str.toCharArray();
for (char c : ch) {
   int temp = (int) c;
   int temp_integer = 64; //for upper case
   if (temp <= 90 & temp >= 65)
      System.out.print(temp-temp_integer);
}
  

输出将为-:456789

答案 1 :(得分:0)

Strategy模式可以为您节省大量时间,并为您提供最大的灵活性。假设我们将AlphabetConverter接口定义为:

@FunctionalInterface
interface AlphabetConverter {
    String convert(char ch);
}

然后,将接受convertAlphabet的{​​{1}}方法定义为:

AlphabetConverter

现在,您可以实现public String convertAlphabet(String actual, AlphabetConverter converter) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < actual.length(); i++) { sb.append(converter.convert(actual.charAt(i))); } return sb.ToString(); } ,一种实现用AlphabetConverter字母代替,一种实现String数组,甚至可以使用lambda函数。