Given a String like this: String secret = “H)86(e,@€l:-;l?,;5o” they ask me to make a new String with only the letters (and spaces if they are) to reveal a secret message….
I tried with a for loop and the charAt method, but it didn’t work… ideas? I would appreciate plain explanation as I’m noob on programming. Thanks!!
CodePudding user response:
Use a „regular expression“ (RegEx) and https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#replaceAll-java.lang.String-java.lang.String- to strip out all unwanted characters.
Something like this will do:
var hello = "H)86(e,@€l:-;l?,;5o".replaceAll("[^a-zA-Z\\s]","");
CodePudding user response:
Have you tried a regular expression that matches only letters and space?
like this: "[a-zA-Z ]*"
CodePudding user response:
You can do that by a regular expression (regex
) in String#replaceAll(regexString, replaceString)
.
String decrypted = secret.replaceAll("[^A-Za-z ]", "");
This will find everything, except A to Z, a to z, space and will replace it by "" (nothing).
You can test such expressions here: https://regex101.com/