We have a String, and we want to convert all the characters if it's inside the HashMap. It will convert the character but it will keep the original character and I want to remove it. I tried doing i+1. Also, is it possible to improve the code, to let it detect if the string contains the character, it will converts on it owns? In other words, can I remove all these if statement and still do the job?
Current result:
Red is Redr Yellow is Yellowy GRedreen is Green and what's RedrGreenb?
Expected result:
Red is Red Yellow is Yellow GRedeen is Green and what's RedGredeenb?
import java.util.HashMap;
public class Test {
public static void main (String [] args){
HashMap<Character,String> convert = new HashMap<Character, String>();
convert.put('r',"Red");
convert.put('y',"Yellow");
convert.put('g',"Green");
String str = "Red is r Yellow is y Green is g and what's rgb?";
String res = "";
for (int i = 0; i< str.length();i++){
if (str.charAt(i) == 'r') {
res += convert.get('r');
// i++;
}
if (str.charAt(i) == 'y') {
res += convert.get('y');
// i++;
}
if (str.charAt(i) == 'g') {
res += convert.get('g');
//i++;
} else {
res += str.charAt(i);
}
}
System.out.println(res);
}
}
Aucun commentaire:
Enregistrer un commentaire