String replace is not performing swap

Asked

Viewed 37 times

0

I am not able to alter the character of my string with that of the map value, 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);
    }
}

1 answer

0

Substitute ch == entry.getKey() for ch.equals(entry.getKey()).

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.