An alternative is to create a Map
that maps each character that will be replaced by its respective letter, and use a StringBuilder
to make the replacements:
String texto = "2n1v5rs0 5 t2d0 0 q25 5x1st5 f1s1c4m5nt5, 1ncl21nd0 t0d0s 0s";
Map<Character, Character> trocas = new HashMap<Character, Character>();
trocas.put('4', 'a'); // troca o "4" por "a"
trocas.put('5', 'e'); // troca o "5" por "e"
trocas.put('1', 'i'); // e assim por diante
trocas.put('0', 'o');
trocas.put('2', 'u');
StringBuilder sb = new StringBuilder(texto);
for (int i = 0; i < sb.length(); i++) {
char ch = sb.charAt(i);
if (trocas.containsKey(ch)) {
sb.setCharAt(i, trocas.get(ch));
}
}
String novoTexto = sb.toString();
To another answer uses replace
, which also works, but every call from replace
creates a new String
. Using an instance of StringBuilder
, I do all the replacements on it and only at the end I Gero the new String
.
Another alternative is to get the array of char
's of String
using toCharArray
, make the replacements in this array and at the end use it to create the new String
:
Map<Character, Character> trocas = etc... // igual ao código anterior
char[] charArray = texto.toCharArray();
for (int i = 0; i < charArray.length; i++) {
char ch = charArray[i];
if (trocas.containsKey(ch)) {
charArray[i] = trocas.get(ch);
}
}
String novoTexto = new String(charArray);
This alternative also avoids creating multiple strings, generating a new one only at the end.