String replace method-help | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
+ 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"

29th Jun 2019, 6:46 AM
Kristína - avatar
3 ответов
+ 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);
29th Jun 2019, 7:12 AM
KrOW - avatar
+ 2
.replace() e to $ o to e $ to o
29th Jun 2019, 8:47 AM
+ 1
Thanks a lot 😃
29th Jun 2019, 10:36 AM
Kristína - avatar