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

后端 未结 1 937
臣服心动
臣服心动 2021-01-18 18:40

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 t

1条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-18 19:21

    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.

    0 讨论(0)
提交回复
热议问题