How can I remove punctuation from input text in Java?

后端 未结 5 1181

I am trying to get a sentence using input from the user in Java, and i need to make it lowercase and remove all punctuation. Here is my code:

    String[] wo         


        
5条回答
  •  悲&欢浪女
    2020-12-02 07:25

    This first removes all non-letter characters, folds to lowercase, then splits the input, doing all the work in a single line:

    String[] words = instring.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+");
    

    Spaces are initially left in the input so the split will still work.

    By removing the rubbish characters before splitting, you avoid having to loop through the elements.

提交回复
热议问题