How to decode a code that modifies vowels

Asked

Viewed 72 times

1

I am trying to create a code that modifies vowels. As an example of an input would be:

2n1v5rs0 5 t2d0 0 q25 5x1st5 f1s1c4m5nt5, 1ncl21nd0 t0d0s 0s ...

and the exit would be:

universe and everything that exists physically, including all ...

I thought I’d start the code with something like this:

Scanner reader = new Scanner(System.in);

if()
    char a = reader.next().charAt(4);
    char e = reader.next().charAt(5);
    char i = reader.next().charAt(1);
    char o = reader.next().charAt(0);
    char u = reader.next().charAt(2);
else 

But I don’t know what to put in if and else.

2 answers

0

Use the method public String replace(char oldChar, char newChar)

import java.io.*;
public class Test {

 public static void main(String args[]) {
   String Str = new String("2n1v5rs0 5 t2d0 0 q25 5x1st5 f1s1c4m5nt5, 1ncl21nd0 t0d0s 0s");

   Str = Str.replace("1", "i");
   Str = Str.replace("2", "u");
   Str = Str.replace("0", "o");
   Str = Str.replace("4", "a");
   Str = Str.replace("5", "e");
   System.out.print(Str);
 }
}

0

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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.