The user enters the formula in the form of a String consisting of letters and symbols
- and + for example:

 String s = "b+c-a+b"; 

If a=4 b=5 c=2 , then how to make it easier for the specified String to become respectively s = "5+2-4+5"; ?

 HashMap<String, String> map = new HashMap<String, String>();; String s = "b+c-a+b"; ArrayList<String> arraylist2 = new ArrayList<String>( Arrays.asList("4","5", "2")); ArrayList<String> arraylist1 = new ArrayList<String>( Arrays.asList("a","b", "c")); char cInput; for (int k = 0; k<arraylist1.size(); k++){ map.put(arraylist1.get(k), arraylist2.get(k)); } String res = ""; for(int i=0; i<s.length(); i++){ cInput = s.charAt(i); String tmp = Character.toString(cInput); if (map.containsKey(tmp)) tmp = map.get(tmp); res += tmp; System.out.println(res); } System.out.println(res); 

Result: 5 + 2-4 + 5

    1 answer 1

    If you work with the replacement of characters, then it is more logical to store Character , rather than String , in the map. Also, if you collect a String from characters or from strings, it is better and easier to use StringBuilder .

     public static void main(String[] args) { Map<Character, Character> map = new HashMap<>(); map.put('a', '4'); map.put('b', '5'); map.put('c', '2'); String s = "b+c-a+b"; char[] chars = s.toCharArray(); StringBuilder result = new StringBuilder(); for (char aChar : chars) { if (map.containsKey(aChar)) { result.append(map.get(aChar)); } else { result.append(aChar); } } System.out.println(result); } 

    Or you can use the trendy Stream API .

     StringBuilder result = s.chars() .mapToObj(i -> map.containsKey((char) i) ? map.get((char) i) : (char) i) .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append);