猿问

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

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


//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 循环?


慕雪6442864
浏览 156回答 2
2回答

RISEBY

对于小写使用这个:String str = "abcdef";char[] ch&nbsp; = str.toCharArray();for (char c : ch) {&nbsp; &nbsp;int temp = (int) c;&nbsp; &nbsp;int temp_integer = 96; //for lower case&nbsp; &nbsp;if (temp <= 122 & temp >= 97)&nbsp; &nbsp; &nbsp; System.out.print(temp-temp_integer);}输出将是 -:123456对于大写:String str = "DEFGHI";char[] ch&nbsp; = str.toCharArray();for (char c : ch) {&nbsp; &nbsp;int temp = (int) c;&nbsp; &nbsp;int temp_integer = 64; //for upper case&nbsp; &nbsp;if (temp <= 90 & temp >= 65)&nbsp; &nbsp; &nbsp; System.out.print(temp-temp_integer);}输出将是 -:456789

人到中年有点甜

策略模式可以为您节省大量时间并为您提供最大的灵活性。假设我们定义一个AlphabetConverter接口,如下:@FunctionalInterfaceinterface AlphabetConverter {&nbsp; &nbsp; String convert(char ch);}然后,将convertAlphabet接受 的方法定义AlphabetConverter为:public String convertAlphabet(String actual, AlphabetConverter converter) {&nbsp; &nbsp; StringBuilder sb = new StringBuilder();&nbsp; &nbsp; for (int i = 0; i < actual.length(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; sb.append(converter.convert(actual.charAt(i)));&nbsp; &nbsp; }&nbsp; &nbsp; return sb.ToString();}现在,您可以实现AlphabetConverter,一个用于替换String字母表,一个用于int数组,甚至可以使用 lambda 函数。
随时随地看视频慕课网APP

相关分类

Java
我要回答