java 如何替换用户输入字符串中除一个之外的所有字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7940053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to replace all characters in a user input string except one
提问by awfulwaffle
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.
我目前正在学习入门级 Java 课程,并且正在研究经典短语猜测作业。目的是让一个用户输入一个秘密短语,另一个用户一次猜一个字母。在猜测之间,除了正确猜测的字母外,该短语必须显示为所有问号。到目前为止,我们的课程只真正涵盖了一些非常基本的方法、if-else 语句和循环,但我正在尝试研究一些可能使这更容易一些的字符串方法。
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.
我知道replace()
,replaceAll()
和contains()
方法,但想知道是否有一种方法可以让您替换字符串中除一个字符之外的所有字符。
Thanks in advance
提前致谢
回答by NPE
The easiest way is probably to use String.replaceAll()
:
最简单的方法可能是使用String.replaceAll()
:
String out = str.replaceAll("[^a]", "?");
This will leave all letters a
intact and will replace all other characters with question marks.
这将使所有字母a
保持完整,并将用问号替换所有其他字符。
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.
这将让所有的信件a
,e
并o
和其他会取代一切。