I need help to do my exercises. I want to replace letters ‘a’ with an ‘e’ in a phrase. For the input: "are you angry"
the output should be: "ere you engry"
.
I tried this but I can't fix it.
public static void main (String [] args){
String s= "are you angry";
remplaceLettre(s);
}
public static void remplaceLettre(String s){
char converted = 0;
String w = "e";
for (int i = 0; i < s.length(); i ) {
if (s.charAt(i) =='a') {
converted = Character.toUpperCase(s.charAt(i));
w = s.replace(s.charAt(i), converted);
s = w;
} else {
converted = Character.toUpperCase(s.charAt(i));
w = s.replace(s.charAt(i), converted);
s = w;
}
}
System.out.println(s);
}
}
output : "are you angry"
Expected output : "ere you engry"
CodePudding user response:
You can use String.replace method like this:
public static void remplaceLettre(String s){
System.out.println(s.replace("a", "e"));
}
If you must use case insensitive replace try this:
s.replaceAll("(?i)a", "e")
CodePudding user response:
package com.khan.vaquar;
public class Test {
public static void main(String[] args) {
String str = "are you angry";
char replaceWith = 'e';
int index[] = { 0, 8 }; //here you can add index want to replace
replaceLettre(str, replaceWith, index);
}
public static String replaceLettre(String str, char ch, int[] index) {
if (null == str) {
return str;
}
char[] chars = str.toCharArray();
for (int i = 0; i < index.length; i ) {
chars[index[i]] = ch;
}
System.out.println(String.valueOf(chars));
return String.valueOf(chars);
}
}
Output : ere you engry