根据hashmap检查字符串

时间:2015-11-20 13:04:43

标签: java string hash morse-code

我想构建一个将英语翻译成莫尔斯语代码的程序,反之亦然,我已经决定使用哈希映射来做到这一点,但我不确定如何通过哈希映射运行字符串并获得最后翻译出来。这是我目前的代码:

import java.util.HashMap;
import java.util.Map;

public class MorseCodeTranslator{

public static String translateToMorseCode() {
    String englishtoMorse = "";
    String translation = null;

    Map<Character, String> morse = new HashMap<Character, String>();
    morse.put('a', "._");
    morse.put('b', "_...");
    morse.put('c',  "_._");
    morse.put('d',  "_..");
    morse.put('e',    ".");
    morse.put('f', ".._.");
    morse.put('g',  "__.");
    morse.put('h', "....");
    morse.put('i',   "..");
    morse.put('j', ".___");
    morse.put('k',   "_.");
    morse.put('l', "._..");
    morse.put('m',   "__");
    morse.put('n',   "_.");
    morse.put('o',  "___");
    morse.put('p', ".__.");
    morse.put('q', "__._");
    morse.put('r', "._.");
    morse.put('s',  "...");
    morse.put('t',   "_");
    morse.put('u',  ".._");
    morse.put('v', "..._");
    morse.put('w',  ".__");
    morse.put('x', "_.._");
    morse.put('y', "_.__");
    morse.put('z', "__..");

    return translation;
}    

public static String translateFromMorseCode() {
    String morsetoEnglish = "";
    String translation = null;

    Map<Character, String> morse = new HashMap<Character, String>();
    morse.put('a', "._");
    morse.put('b', "_...");
    morse.put('c',  "_._");
    morse.put('d',  "_..");
    morse.put('e',    ".");
    morse.put('f', ".._.");
    morse.put('g',  "__.");
    morse.put('h', "....");
    morse.put('i',   "..");
    morse.put('j', ".___");
    morse.put('k',   "_.");
    morse.put('l', "._..");
    morse.put('m',   "__");
    morse.put('n',   "_.");
    morse.put('o',  "___");
    morse.put('p', ".__.");
    morse.put('q', "__._");
    morse.put('r', "._.");
    morse.put('s',  "...");
    morse.put('t',   "_");
    morse.put('u',  ".._");
    morse.put('v', "..._");
    morse.put('w',  ".__");
    morse.put('x', "_.._");
    morse.put('y', "_.__");
    morse.put('z', "__..");  

    return translation;
}
}  

我希望能够通过哈希映射运行englishtoMorsemorsetoEnglish中的任何内容,并将字符转换为哈希映射中与之关联的值,然后在{{1}中输出它们}}

6 个答案:

答案 0 :(得分:3)

将地图创建为静态字段。添加莫尔斯字母表。然后创建一个方法 获取要翻译的文本作为参数。然后迭代文本以翻译每个字符并使用已翻译的字符创建将返回的字符串。

我用你的代码和我的解释做了一个例子。 该代码仅适用于莫尔斯的英文文本。你必须添加另一个方向。

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{

    private static final Map<Character, String> morse = new HashMap<Character, String>();
    static {
    morse.put('a', "._");
    morse.put('b', "_...");
    morse.put('c',  "_._");
    morse.put('d',  "_..");
    morse.put('e',    ".");
    morse.put('f', ".._.");
    morse.put('g',  "__.");
    morse.put('h', "....");
    morse.put('i',   "..");
    morse.put('j', ".___");
    morse.put('k',   "_.");
    morse.put('l', "._..");
    morse.put('m',   "__");
    morse.put('n',   "_.");
    morse.put('o',  "___");
    morse.put('p', ".__.");
    morse.put('q', "__._");
    morse.put('r', "._.");
    morse.put('s',  "...");
    morse.put('t',   "_");
    morse.put('u',  ".._");
    morse.put('v', "..._");
    morse.put('w',  ".__");
    morse.put('x', "_.._");
    morse.put('y', "_.__");
    morse.put('z', "__..");
    morse.put(' ', " ");
    }
    public static void main (String[] args) throws java.lang.Exception
    {
        String str = "Hello World";
        System.out.println(translate(str));
    }



    public static String translate(String text) {
        StringBuilder builder = new StringBuilder();
        String lower = text.toLowerCase();
        for (int i = 0; i < text.length(); i++) {
            builder.append(morse.get(lower.charAt(i)));
        }
        return builder.toString();
    }    

}

输出:

......_..._..___ ._____._.._.._..

工作示例:

http://ideone.com/uWGAtU

答案 1 :(得分:1)

对于“English to Morse”用例,请使用for这样的循环:

StringBuilder sb = new StringBuilder();
for ( int i = 0; i < englishtoMorse.length(); i++) {
    char c = englishtoMorse.charAt(i);
    sb.append(morse.get(c));
}
translate = sb.toString();

至于“莫尔斯英语”用例,你需要在莫尔斯字符之间使用某种分隔符。否则,您将得到仅包含'e'和't'的翻译。我们假设,您的morseToEnglish字符串在字符之间使用空格作为分隔符。然后你可以这样翻译:

StringTokenizer st = new StringTokenizer(morseToEnglish);
StringBuilder result = new StringBuilder();
while( st.hasMoreTokens()) {
    result.append(morse.findKey(st.nextToken()));
}
translation = sb.toString();

我希望这会有所帮助。

答案 2 :(得分:1)

您应该初始化地图一次(例如,在静态数据成员中,如Zelldon建议的那样)。完成后,通过使用Java 8的流API,可以非常优雅地将字符串从英语翻译成莫尔斯:

public static String translateToMorseCode(String english) {
    return english.chars()
                  .boxed()
                  .map(c -> morse.get((char) c.intValue()))
                  .collect(Collectors.joining());
}

编辑:
正如JB Nizet评论的那样,使用mapToObj会更优雅(也许是高效的):

public static String translateToMorseCode(String english) {
    return english.chars()
                  .mapToObj(c -> morse.get((char) c))
                  .collect(Collectors.joining());
}

答案 3 :(得分:0)

您可以在此处使用data = {} data['id'] = 3 # ... data['display_name'] = 'Chem 101' # ... summary = course_summary_struct._make([data[x] for x in course_summary_struct._fields]) 。我认为它更适合你的情况。

BiMap

您可以使用BiMap<Character, String> biMap = HashBiMap.create(); biMap.put('a', "._"); biMap.put('b', "_.."); System.out.println("morse code = " + biMap.get('a')); System.out.println("alphabet = " + biMap.inverse().get("._")); 。访问link

答案 4 :(得分:0)

您可以根据需要使用HashMap:

    import java.util.HashMap;
    import java.util.Map;

    public class MorseCodeTranslator{
    public static Map<Character, String> morse = new HashMap<Character, String>();
    public static Map<String, Character> english = new HashMap<>();
    public MorseCodeTranslator(){
    morse.put('a', "._");
    morse.put('b', "_...");
    morse.put('c',  "_._");
    morse.put('d',  "_..");
    morse.put('e',    ".");
    morse.put('f', ".._.");
    morse.put('g',  "__.");
    morse.put('h', "....");
    morse.put('i',   "..");
    morse.put('j', ".___");
    morse.put('k',   "_.");
    morse.put('l', "._..");
    morse.put('m',   "__");
    morse.put('n',   "_.");
    morse.put('o',  "___");
    morse.put('p', ".__.");
    morse.put('q', "__._");
    morse.put('r', "._.");
    morse.put('s',  "...");
    morse.put('t',   "_");
    morse.put('u',  ".._");
    morse.put('v', "..._");
    morse.put('w',  ".__");
    morse.put('x', "_.._");
    morse.put('y', "_.__");
    morse.put('z', "__..");
    morse.forEach( (c,s) -> english.put(s, c));
    }


    public static String translateToMorseCode(final String english) {
    char[] data = english.toCharArray();
    StringBuilder result = new StringBuilder();
    for(char c: data) result.append(morse.get(new Character(c)));
    return result.toString();
    }

    public static String translateFromMorseCode(final String morseCode) {
    String[] data = morseCode.split(" ");
    StringBuilder result = new StringBuilder();
    for(String s:data) result.append(english.get(s));
    return result.toString();
    }
    }

答案 5 :(得分:0)

使用一个表并使用Map.entrySet()进行向后搜索。并且不要忘记分隔符令牌。

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.StringTokenizer;

public class MorseCodeTranslator{
    public static Map<Character, String> getMorseTable(){
        Map<Character, String> morse = new HashMap<Character, String>();
        morse.put('a', "._");
        morse.put('b', "_...");
        morse.put('c',  "_._");
        morse.put('d',  "_..");
        morse.put('e',    ".");
        morse.put('f', ".._.");
        morse.put('g',  "__.");
        morse.put('h', "....");
        morse.put('i',   "..");
        morse.put('j', ".___");
        morse.put('k',   "_.");
        morse.put('l', "._..");
        morse.put('m',   "__");
        morse.put('n',   "_.");
        morse.put('o',  "___");
        morse.put('p', ".__.");
        morse.put('q', "__._");
        morse.put('r', "._.");
        morse.put('s',  "...");
        morse.put('t',   "_");
        morse.put('u',  ".._");
        morse.put('v', "..._");
        morse.put('w',  ".__");
        morse.put('x', "_.._");
        morse.put('y', "_.__");
        morse.put('z', "__..");
        return morse;
    }
    public static String toMorse(String text){      
        Map<Character, String> table  = getMorseTable();
        StringBuilder result = new StringBuilder();
        // get every char in text
        for(int i = 0; i < text.length(); i++){
            char c = text.charAt(i);
            // and add morse character from table
            result.append(table.get(c));
            // put character separator
            result.append("|");
        }
        // delete last character separator
        result.deleteCharAt(result.length() - 1);
        return result.toString();
    }

    public static String fromMorse(String morse){
        Map<Character, String> table  = getMorseTable();
        // use string tokenizer to separate morse characters
        StringTokenizer st = new StringTokenizer(morse,"|");
        StringBuilder result = new StringBuilder();
        // get every morse character
        while( st.hasMoreTokens()) {
            String morseChar = st.nextToken();
            // and find equivalent letter in morse table
            for (Entry<Character, String> entry : table.entrySet()) {
                if (entry.getValue().equals(morseChar)) {
                   result.append(entry.getKey());
                   break;
                }
            }
        }
        return result.toString();
    }

    public static void main(String[] args){
        String text = "abcxyz";
        System.out.println(text);
        String morse = toMorse(text);
        System.out.println(morse);
        String back = fromMorse(morse);
        System.out.println(back);
    }
}

输出:

abcxyz
._|_...|_._|_.._|_.__|__..
abcxyz