Search code examples
javastringfor-loopcompare

Create a String from other String in Java


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!!


Solution

  • 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/