How to Remove Special Characters from String in Java?12 Feb 2025 | 6 min read 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. Using Java String.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: Java Program to Remove Special CharacterIn the following example, the removeAll() method removes all the special characters from the string and puts a space in place of them. RemoveSpecialCharacterExample1.java Output This string contains special characters Example In the following example, we are replacing all the special character with the space. RemoveSpecialCharacterExample2.java Output Hello Java Programmer ! Using User Defined LogicIn 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 returns 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. RemoveSpecialCharacterExample3.java Output String after removing special characters: ProgrammingLanguage Using Character.isLetter() with StringBuilderUsing Character.isLetter() in combination with StringBuilder provides an efficient way to filter out non-alphabetic characters from a string in Java. The approach leverages the ability of Character.isLetter() to identify letters and the mutability of StringBuilder to construct the cleaned string dynamically. Step 1: Create a String variable originalString and initialize it with "Hello@# World$%^&*()_+123!" and also create a StringBuilder object cleanedString to store the resulting string. Step 2: Convert the originalString to a character array using toCharArray() and use an enhanced for Loop to iterate through each character in the character array. Step 3: For each character c in the character array:
Step 4: Convert the StringBuilder object cleanedString to a String using toString() and Print the resulting string. Let's implement the above logic in a Java program. UsingCharater.java Output: HelloWorld Without Using Built-in MethodsIn scenarios where using built-in methods is restricted or to gain a deeper understanding of character processing, we can manually filter alphabetic characters from a string by directly comparing their ASCII values. This approach ensures control over each step of the character validation process. AlgorithmStep 1: Create a String variable originalString and initialize it with "Hello@# World$%^&*()_+123!" and also create a StringBuilder object cleanedString to store the resulting string. Step 2: Use a for Loop to iterate through each character in the originalString by its index. Step 3: For each character at the current index in the Loop:
Step 4: Convert the StringBuilder object cleanedString to a String using toString(). WithoutBuiltin.java Output: HelloWorld Using Regex in JavaIn Java, regular expressions (regex) offer a robust solution for string processing tasks. Previously, we utilized the replaceAll() method to eliminate special characters from strings, a task that can also be achieved through regex. With regex, the replaceAll() method utilizes the '^' character to select all characters except those specified, enabling precise removal or replacement operations. AlgorithmStep 1: Create a String variable originalString and initialize it with "Hello@# World$%^&*()_+123!". Step 2: Use the replaceAll method of the String class to replace all non-alphabetic characters in originalString with an empty string. The regex pattern [^a-zA-Z] is used to match any character that is not a letter. Step 3: Store the result of the replaceAll method in a new String variable cleanedString and print the value of cleanedString. UsingRegex.java Output: HelloWorld Next TopicJava Tutorial |
A string is given that is made only of digits, such that the string represents a number. Our task is to split the number string in such a way that each segment of the number that is formed after the split is a prime number. Also,...
10 min read
Difference between () and Line() In Java, the Scanner class available in the java.util.package is one of the easiest ways for obtaining input of the primitive data types such as int, double, and strings. In competitive programming, time is a constraint, and using the Scanner class is...
4 min read
The javax.naming.CompositeName class has an endsWith() method. The CompositeName class is used to determine whether or not a composite name that is passed in as an argument is a suffix of this particular composite name. If the object of this composite name ends in "X," then...
2 min read
Java Multithreading is an essential feature that allows developers to write programs that can run concurrently on multiple threads. It helps developers to create responsive applications and improve the performance of the software. Many books have been written on this topic, providing in-depth knowledge of multithreading...
4 min read
The problem of counting the number of ways to cover a distance can be stated as the mere generalization to ''staircase'' problem where the only difference is that a person can take at most three steps to cover a given distance. This simplifies the logistics...
8 min read
Java, a strong and flexible programming language, has long been a mainstay of the software development sector. Java has remained relevant and well-liked since its introduction in the middle of the 1990s, making it a great option for anybody wishing to enter the programming profession or...
4 min read
In Java, initializing a static map enables the creation of a map object associated with a class rather than an instance of the class. This allows the map to be shared among all instances of the class and accessed without creating an object. Static maps are...
7 min read
In Java, creating test cases for exceptions is not a difficult task. The JUnit testing tool of Java provides a way to track the exception handling of code. We can write the test cases to check whether the code throws a desired exception or not. In order...
4 min read
Java offers a number of data systems that allow the developers to work with collections of records effectively. When more than one threads are involved, concurrent collections come to be essential to make sure data integrity and thread safety. In this section, we will discover concurrent...
5 min read
? Every software application requires a username and password in order to authenticate the valid user. A username can be anything like an email-id or just a combination of characters. But while creating a password, one must be very careful. Because anyone with valid credentials can enter...
10 min read
We request you to subscribe our newsletter for upcoming updates.
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