Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace all characters in a user input string except one

I'm currently in an introductory level Java class, and am working on the classic phrase guess assignment. The object is for one user to enter a secret phrase, and another to guess it one letter at a time. Between guesses, the phrase must be displayed as all question marks except the letters that were guessed correctly. Our class has only really covered some very basic methods, if-else statements and loops up to this point, but I'm trying to research some string methods that may make this a bit easier.

I know of the replace(), replaceAll() and contains() methods, but was wondering if there is a method which allows you to replace all but one character of your choice in a string.

Thanks in advance

like image 721
awfulwaffle Avatar asked Oct 29 '11 16:10

awfulwaffle


People also ask

How do you replace all occurrences of a character in a string?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag. replaceAll() method is more straight forward.

How do you replace all characters except numbers in Java?

Method 2: Using String.replaceAll() Non-alphanumeric characters comprise of all the characters except alphabets and numbers.


1 Answers

The easiest way is probably to use String.replaceAll():

String out = str.replaceAll("[^a]", "?");

This will leave all letters a intact and will replace all other characters with question marks.

This can be easily extended to multiple characters, like so:

String out = str.replaceAll("[^aeo]", "?");

This will keep all letters a, e and o and will replace everything else.

like image 161
NPE Avatar answered Sep 30 '22 15:09

NPE