我编写了这段代码,用自定义提供的字母替换字符串中的字符:
//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 循环?
RISEBY
人到中年有点甜
相关分类