How to Remove Special Characters from String in Java
A character which is not an alphabet or numeric character is called a special character. We should remove all the special characters from the string so that we can read the string clearly and fluently. Special characters are not readable, so it would be good to remove them before reading.
Java replaceAll() method
Java replaceAll() method of String class replaces each substring of this string that matches the given regular expression with the replacement.
This method accepts two parameters:
It returns the resultant String. It throws PatternSyntaxException if the regular expression syntax is invalid. The above method yields the same result as the expression:
Example of removing special characters using replaceAll() method
In the following example, the removeAll() method removes all the special characters from the string and puts a space in place of them.
This string contains special characters
In the following example, we are replacing all the special character with the space.
Hello Java Programmer !
Example of removing special characters using user defined logic
In the following example, we are defining logic to remove special characters from a string. We know that the ASCII value of capital letter alphabets starts from 65 to 90 (A-Z) and the ASCII value of small letter alphabet starts from 97 to 122 (a-z). Each character compare with their corresponding ASCII value. If both the specified condition return true it return true else return false. The for loop executes till the length of the string. When the string reaches its size, it terminates execution and we get the resultant string.
String after removing special characters: ProgrammingLanguage