How to Remove Special Characters from String in JavaA 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() methodJava replaceAll() method of String class replaces each substring of this string that matches the given regular expression with the replacement. Syntax 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. Output This string contains special characters Example In the following example, we are replacing all the special character with the space. Output 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. Output String after removing special characters: ProgrammingLanguage Next TopicJava Tutorial |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India