String replace is not performing exchange

0

I can not change the character of my string with the value of the map, if they are equal: key and character.

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

public class Mapa {

    public static Map<Character, Character> mapa;

    public static void main(String[] args) {

        mapa = new HashMap<>();

        mapa.put('á', 'a');
        mapa.put('é', 'e');
        mapa.put('í', 'i');
        mapa.put('ó', 'o');
        mapa.put('ú', 'u');

        String str = "cása";        
        for(int i=0; i < str.length(); i++) {
            Character ch = str.charAt(i);
            for(Entry<Character, Character> entry : mapa.entrySet()) {
                if(ch == entry.getKey()) {
                    str = str.replace(ch, entry.getValue());
                }
            }
        }

        // Aqui esta retornando a mesma string.
        System.out.println(str);
    }
}
    
asked by anonymous 14.04.2018 / 19:36

1 answer

0

Replace ch == entry.getKey() with ch.equals(entry.getKey()) .

== checks whether the two references point to the same instance of an object. Already the implementation of the equals method in the Character class verifies that their values are equal.

    
14.04.2018 / 19:58