如何替换用户输入字符串中除一个以外的所有字符 [英] How to replace all characters in a user input string except one
问题描述
我目前正在学习入门级Java课,并且正在研究经典的短语猜测作业。该对象是让一个用户输入一个秘密短语,而另一个用户一次输入一个字母。在猜测之间,该短语必须显示为所有问号,但正确猜测的字母除外。到目前为止,我们的课程仅涵盖了一些非常基本的方法,if-else语句和循环,但是我正在尝试研究一些字符串方法,这些方法可能会使这变得容易一些。
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.
我知道 replace()
, replaceAll()
和 contains()
方法,但是想知道是否有一种方法可以替换字符串中除一个字符以外的所有字符。
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.
预先感谢
推荐答案
最简单的方法可能是使用 String.replaceAll()
:
The easiest way is probably to use String.replaceAll()
:
String out = str.replaceAll("[^a]", "?");
这将保留所有 a
字母,
这可以很容易地扩展为多个字符,例如:
This can be easily extended to multiple characters, like so:
String out = str.replaceAll("[^aeo]", "?");
这将保留所有字母 a
, e
和 o
,并将替换所有其他内容。
This will keep all letters a
, e
and o
and will replace everything else.
这篇关于如何替换用户输入字符串中除一个以外的所有字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!