Javatpoint Logo
Javatpoint Logo

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.

Syntax

This method accepts two parameters:

  • regex: It is the regular expression to which string is to be matched. It may be of different types.
  • replacement: The string to be substituted for the match.

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




Help Others, Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA