+ 1
String replace method-help
I need to replace letters in a word, for example "e" to "o" and "o" to "e", so the final output for the word "hello" would be "holle" My solutions always change every letter, so instead of "holle" I get " helle" or " hollo"
3 Réponses
+ 4
You can loop on string chars and edit another string buffer for get final replaced string... A sample:
String str= "Hello world";
StringBuilder sb= new StringBuilder(str.length());
for(int i=0; i<str.length(); ++i){
char c= str.charAt(i);
if(c=='e'){
c='o';
}else if(c=='o'){
c= 'e';
}
sb.append(c);
}
System.out.println(sb);
+ 2
.replace()
e to $
o to e
$ to o
+ 1
Thanks a lot 😃