简体   繁体   中英

How can I use HashMap values to form a String?

I have the following code that maps specific String characters into letters:

 String a = "94466602777330999666887770223377778077778 883 336687777";
    String[] tokens = a.split("(?<=(.))(?!\\1)");
    Map<String, String> hmap = new HashMap<String, String>();

    hmap.put("2", "A");
    hmap.put("22", "B");
    hmap.put("222", "C");
    hmap.put("3", "D");
    hmap.put("33", "E");
    hmap.put("333", "F");
    hmap.put("4", "G");
    hmap.put("44", "H");
    hmap.put("444", "I");
    hmap.put("5", "J");
    hmap.put("55", "K");
    hmap.put("555", "L");
    hmap.put("6", "M");
    hmap.put("66", "N");
    hmap.put("666", "O");
    hmap.put("7", "P");
    hmap.put("77", "Q");
    hmap.put("777", "R");
    hmap.put("7777", "S");
    hmap.put("8", "T");
    hmap.put("88", "U");
    hmap.put("888", "V");
    hmap.put("9", "W");
    hmap.put("99", "X");
    hmap.put("999", "Y");
    hmap.put("9999", "Z");
    hmap.put("1", ".");
    hmap.put("0", " ");

After doing HashMap, I want to return a String That coverts my previous String "94466602777330999666887770223377778077778 883 336687777" into "WHO ARE YOUR BEST STUDENTS"

As you have mentioned, you already divided your input in strings array.

StringBuilder builder = new StringBuilder();

for (String s: tokens) {           
    builder.append(hmap.get(s));
}

String result = builder.toString();

您可以使用StringBuilder类形成String。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM