How can I remove punctuation from input text in Java?

后端 未结 5 1180

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:41

    If you don't want to use RegEx (which seems highly unnecessary given your problem), perhaps you should try something like this:

    public String modified(final String input){
        final StringBuilder builder = new StringBuilder();
        for(final char c : input.toCharArray())
            if(Character.isLetterOrDigit(c))
                builder.append(Character.isLowerCase(c) ? c : Character.toLowerCase(c));
        return builder.toString();
    }
    

    It loops through the underlying char[] in the String and only appends the char if it is a letter or digit (filtering out all symbols, which I am assuming is what you are trying to accomplish) and then appends the lower case version of the char.

提交回复
热议问题