Replace alphabet in a string using replace?

前端 未结 4 1612
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-19 14:20

I\'m wondering if I can use string.replace() to replace all alphabets in a string?

String sentence = \"hello world! 722\"
String str = sentence         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-19 14:44

    Use String#replaceAll that takes a Regex:

    str = str.replaceAll("[a-zA-Z]", "@");
    

    Note that String#replace takes a String as argument and not a Regex. If you still want to use it, you should loop on the String char-by-char and check whether this char is in the range [a-z] or [A-Z] and replace it with @. But if it's not a homework and you can use replaceAll, use it :)

提交回复
热议问题