【问题标题】:Replace character in a String with HashMap [closed]用HashMap替换字符串中的字符[关闭]
【发布时间】:2021-01-06 17:12:26
【问题描述】:

我有一些想法要这样做

我卡在 if 语句部分,如何进行比较?

这个例子的预期输出是:字符串ones is use two test the map numberthree。

      String s = "The string 1s is use 2 test the map number3.";
 
        HashMap<Integer,String> map = new HashMap<>();
        map.put(1,"one");
        map.put(2,"two");
        map.put(3,"three");
  
        for (int i = 0; i < s.length(); i++){
        if (s.charAt(i) is equals to map.contains(1){
           s[i] = map.get(1);
     }
}

【问题讨论】:

    标签: java if-statement hash hashmap equals


    【解决方案1】:

    您需要将字符转换为数值,以检查它是否是HashMap 中的key。更好的方法是使用StringBuilder,因为您要附加String,以防在地图中找到它:

    String s = "The string 1s is use 2 test the map number3.";
    HashMap<Integer,String> map = new HashMap<>();
    map.put(1,"one");
    map.put(2,"two");
    map.put(3,"three");
            
    StringBuilder sb = new StringBuilder();
    for (char c : s.toCharArray()){
        if (Character.isDigit(c) && map.containsKey(Character.getNumericValue(c))){
            sb.append(map.get(Character.getNumericValue(c)));
        }else {
            sb.append(c);
        }
    }
    
    System.out.println(sb.toString());
    

    另一种解决方案是将字符存储为key

    String s = "The string 1s is use 2 test the map number3.";
    HashMap<Character,String> map = new HashMap<>();
    map.put('1',"one");
    map.put('2',"two");
    map.put('3',"three");
                    
    StringBuilder sb = new StringBuilder();
    for (char c : s.toCharArray()){
         if (map.containsKey(c)){
              sb.append(map.get(c));
         }else {
              sb.append(c);
         }
    }
    
    System.out.println(sb.toString());
    

    输出:

    The string ones is use two test the map numberthree.
    

    【讨论】:

      【解决方案2】:

      您可以迭代地图并将地图键替换为字符串中的值。

      for (Map.Entry<Integer,String> e: map.entrySet()) {
        s = s.replace(e.getKey().toString(), e.getValue());
      }
      

      我建议您不要按字符串中的字符进行迭代,因为如果您想替换两个或多个数字,例如 22,您会遇到问题。

      演示:

      String s = "The string 1s is use 2 test the map number3.";
      HashMap<Integer,String> map = new HashMap<>();
      map.put(1,"one");
      map.put(2,"two");
      map.put(3,"three");
      for (Map.Entry<Integer,String> e: map.entrySet()) {
        s = s.replace(e.getKey().toString(), e.getValue());
      }
      System.out.println(s);
      

      输出:

      The string ones is use two test the map numberthree.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-06
        • 1970-01-01
        • 1970-01-01
        • 2013-09-16
        相关资源
        最近更新 更多