如何替换用户输入字符串中除一个字符之外的所有字符
我目前正在学习初级 Java 课程,并且正在做经典的短语猜测作业。目标是让一个用户输入一个秘密短语,另一个用户一次猜一个字母。在猜测之间,短语必须显示为除正确猜测的字母之外的所有问号。到目前为止,我们的课程只真正涵盖了一些非常基本的方法、if-else 语句和循环,但我正在尝试研究一些字符串方法,这些方法可能会使这变得更容易一些。
我知道 replace()
、replaceAll()
和 contains()
方法,但想知道是否有一种方法可以让您替换字符串中除一个字符外的所有字符。
提前致谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最简单的方法可能是使用
String.replaceAll()
:这将使所有字母
a
保持不变,并将替换所有其他字符带有问号。这可以轻松扩展到多个字符,如下所示:
这将保留所有字母
a
、e
和o
并替换其他所有字母。The easiest way is probably to use
String.replaceAll()
: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:
This will keep all letters
a
,e
ando
and will replace everything else.