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[] words = instring.split("\\s+"); for (int i = 0; i < words.length; i++) { words[i] = words[i].toLowerCase(); } String[] wordsout = new String[50]; Arrays.fill(wordsout,""); int e = 0; for (int i = 0; i < words.length; i++) { if (words[i] != "") { wordsout[e] = words[e]; wordsout[e] = wordsout[e].replaceAll(" ", ""); e++; } } return wordsout;
I cant seem to find any way to remove all non-letter characters. I have tried using regexes and iterators with no luck. Thanks for any help.
The standard solution to remove punctuations from a String is using the replaceAll() method. It can remove each substring of the string that matches the given regular expression. You can use the POSIX character class \p{Punct} for creating a regular expression that finds punctuation characters.
Remove Punctuation From String Using the replaceAll() Method in Java. We can use a regex pattern in the replaceAll() method with the pattern as \\p{Punct} to remove all the punctuation from the string and get a string punctuation free. The regex pattern is \\p{Punct} , which means all the punctuation symbols.
We can use replace() method to remove punctuation from python string by replacing each punctuation mark by empty string. We will iterate over the entire punctuation marks one by one replace it by an empty string in our text string.
*)[\\p{P}](. *) ", it will include all preceding and proceeding characters of the punctuation because the matches() requires to match all the sentence.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With