簡體   English   中英

用其morsecode值替換字符串中的多個不同字符

[英]Replacing multiple different characters in a string with their morsecode values

我正在編寫一個程序,它將字符串(用戶輸入)轉換為莫爾斯電碼。 最初,我打算使用大量的if和else if語句,但是在Java中找到了replace / replaceAll函數。 這被證明是非常有用的。 但是,鑒於我的中等編程技能,我不知道如何替換同一字符串中的多個不同字符。 這是代碼的一部分:

  Scanner reader = new Scanner(System.in);
        System.out.print("Enter the text you want translated to 
Morsecode:");
        String input = reader.nextLine();
        String res = "";
        String[] letters = new String[] {"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[] codes = new String[] {".-", "-...", "-.-.", "-..", ".", 
"..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---",  ".-
-.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", 
"-...", "--.."};
        int i=0;
        for (i=0;i<26;i++)
        {

            res = input.replaceAll(letters[i], codes[i]);
        }
        System.out.print(res);

如果我輸入的字符串是“ aabb”,程序將輸出以下結果:“ .-.- bbaa -...-...”,這個結果與期望的結果相差不遠(我認為),但是我無法理解“ bbaa”的來源? 謝謝

編輯:我已經根據一些答案給出的建議編輯了原始問題。 但是,當前編碼僅打印出已輸入到程序中的字符串

您通過replaceAll進入了正確的軌道。 這是完成此程序的方法:

  • 創建兩個String[]數組-一個帶有字母的數組,另一個帶有其相應的摩爾斯電碼
  • 循環遍歷數組,然后調用res = res.replaceAll(letters[i], codes[i]);
  • 替換后應加空格; 否則,您將無法分辨.--...代表ab.- -... )還是ws.-- ...

這兩個數組如下所示:

String[] letters = new String[] {"a", "b", ...};
String[] codes = new String[] {".-", "-...", ...};

注意:完成程序的初始版本后,嘗試通過從數字i中生成字母第i個字母的字符串來嘗試找出消除letters數組的方法。

所有更改都必須應用於相同的字符串:

String s = reader.nextLine();
s = s.replace("a", ".-");
s = s.replace("b", "-...");
System.out.print(s);

另外,出於學習目的,您可能考慮在每個代碼后添加一個空格:“ .-”。

制作一個HashMap ,將字母作為鍵,將莫爾斯電碼作為值。 然后遍歷您的輸入字符串,並為字符串中的每個字符附加適當的摩爾斯電碼以輸出StringBuilder

String input = "Lorem ipsum";

    Map<String, String> charTable = new HashMap<>();
    charTable.put("A", ".-");
    // other characters

    StringBuilder sbOut = new StringBuilder();
    for (int i = 0; i < input.length(); i++) {
        String character = String.valueOf(input.charAt(i));

        sbOut.append(charTable.get(character));
    }

System.out.println(sbOut);

與具有兩個數組的選項相比,這樣做的好處是可讀性更高,調試起來更容易,而且我覺得(我尚未測試過)它的效率也更高。

雖然replaceAll 可以用來完成所需的操作,但效率遠非如此,因為1)您將在每次替換中創建String實例,以及2)您必須多次遍歷源字符串(每個字符一次)您更換)。 一種更有效的方法是維護一個StringBuilder實例,在該實例中將附加轉換后的結果,並使用source.toCharArray()遍歷源字符串。 另外,為了避免輸入多個if語句來替換每個字符的情況,請維護英語字符到其Morse等效項的Map<Character, String>映射。 然后整個替換看起來很簡單:

Map<Character, String> translation = new HashMap<>();
map.put('a', "._");
// repeat for each character representation
// this map can be initialized once, e.g. as a static
StringBuilder result = new StringBuilder("");
for (Character c : input.toCharArray()) {
    result.append(translation.get(c));
}
return result.toString();

我同意,每個字母的String.replaceAll()都可以正常工作。 但是,請不要忘記,每次替換時,JVM都會創建新字符串。 因此,對於長字符串來說,您有許多用於GC的對象。

我提供將String.toCharArray()StringBuilder一起使用,以將給定的字符串轉換為莫爾斯電碼:

public class Morse {
    private static final Map<Character, String> CODE;

    static {
        Map<Character, String> map = new HashMap<>();

        map.put('a', ".-");
        map.put('b', "-...");

        CODE = Collections.unmodifiableMap(map);
    }

    public static String encode(String str) {
        if (str == null)
            return null;

        StringBuilder buf = new StringBuilder();

        for (int i = 0; i < str.length(); i++) {
            String code = CODE.get(str.charAt(i));
            buf.append(code != null ? code : " ");
        }

        return buf.toString();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM