Replace all letters of a String with asterisks

Asked

Viewed 1,997 times

-1

I’m not able to replace all the letters of the word with an asterisk, only a few are being replaced. How do I get them all replaced?

Scanner sc = new Scanner(System.in);
String conversor = null;

System.out.println("Digite a palavra a ser criptografada");
String palavra = sc.nextLine();

for(int i=0;i<palavra.length();i++){
    conversor = palavra.replace(palavra.substring(i), "*");
    System.out.println(conversor);
}

System.out.println(conversor);
sc.close();

inserir a descrição da imagem aqui

  • Do you have to print all these times? Why? Or if you did it to verify the steps and only need the printed asterisks at the end in place of the typed text? And why do you need this? Seems like something meaningless or something too simple to even curl up, is there anything we don’t know about the problem? Any requirement not shown in the question?

  • I put it out to print every time just to find out what was going on inside the for. I’m training in cryptography and they passed me this exercise.

  • I want the entire String to have an asterisk. Encrypted Word = ****** ************

2 answers

3

I am also a fan of regex, but for this case I do not see great needs. I should also disagree a little costamilam response because it replaces things that are not letters by letters, since it keeps only space (the expression [^ ] indicates anything other than the space character ) as original character.

To replace only the letters, I will identify them using Character.isLetter. I will also initially work with a character array to ultimately convert back to string. I’ll get the characters using String.toCharArray and build the new string using the constructor String(char[]).

String palavra = ...; // recebe a palavra, advinda de onde é adequado
char[] caracteres = palavra.toCharArray();

for (int i = 0; i < caracteres.length; i++) {
  if (Character.isLetter(caracteres[i])) {
    caracteres[i] = '*';
  }
}
String palavraModificada = new String(caracteres);

// faz o que deseja com a palavra modificada

1


You can use the method replaceAll passing a regex to replace all letters except space:

"Palavra Criptografada".replaceAll("[^ ]", "*");

By your example in the comments, that’s what you want, but if you need to change specific characters, just adapt the regex

  • That’s just what I wanted !! Thank you boy.

  • Fabio, choose his answer as the best.

Browser other questions tagged

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