Remove all non-alphabetical characters of a String in Java
Given a string str, consisting of non-alphabetical characters. The task is to remove all those non-alphabetical characters of str and print the words on a new line.
Input: str = “Hello, how are you ?”
comma(, ), white space and question mark (?) are removed and there are total 4 words in string s.
Each token is printed in the same order in which it appears in string s.
Input: “Azad is a good boy, isn’ t he ?”
Approach: Non-alphabetic characters are basically any character that is not a number or letter. It can be English alphabetic letters, blank spaces, exclamation points (!), commas (, ), question marks (?), periods (.), underscores (_), apostrophes (‘), and at symbols (@). The approach is to use Java String.split method to split the String, s into an array of substrings. Then print each n words on a new line in the same order as it appears in String s.
Below is the implementation of the above approach:
Hello how are you
Time Complexity: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.