Given a string str, the task is to remove all non-alphanumeric characters from it and print the modified it.
Examples:
Input: @!Geeks-for’Geeks,123
Output: GeeksforGeeks123
Explanation: at symbol(@), exclamation point(!), dash(-), apostrophes(‘), and commas(, ) are removed.Input: Geeks_for$ Geeks?{}[]
Output: GeeksforGeeks
Explanation: underscore(_), dollar sign($), white space, question mark(?), curly braces({}), and square bracket([]) are removed.Input: GeeksforGeeks123
Output: GeeksforGeeks123
Explanation: No need to remove any character, because the given string doesn’t have any non-alphanumeric character.
Method 1: Using ASCII values
Since the alphanumeric characters lie in the ASCII value range of [65, 90] for uppercase alphabets, [97, 122] for lowercase alphabets, and [48, 57] for digits. Hence traverse the string character by character and fetch the ASCII value of each character. If the ASCII value is not in the above three ranges, then the character is a non-alphanumeric character. Therefore skip such characters and add the rest in another string and print it.
Method 2: Using String.replaceAll()
Non-alphanumeric characters comprise of all the characters except alphabets and numbers. It can be punctuation characters like exclamation mark(!), at symbol(@), commas(, ), question mark(?), colon(:), dash(-) etc and special characters like dollar sign($), equal symbol(=), plus sign(+), apostrophes(‘).
The approach is to use the String.replaceAll method to replace all the non-alphanumeric characters with an empty string.
Below is the implementation of the above approach:
Java
// Java program to remove non-alphanumeric// characters from a stringclass GFG { // Function to remove non-alphanumeric // characters from string public static String removeNonAlphanumeric(String str) { // replace the given string // with empty string // except the pattern "[^a-zA-Z0-9]" str = str.replaceAll( "[^a-zA-Z0-9]", ""); // return string return str; } // Driver Code public static void main(String args[]) { // Test Case 1: String str1 = "@!Geeks-for'Geeks, 123"; System.out.println( removeNonAlphanumeric(str1)); // Test Case 2: String str2 = "Geeks_for$ Geeks?{}[]"; System.out.println( removeNonAlphanumeric(str2)); // Test Case 3: String str3 = "GeeksforGeeks123"; System.out.println( removeNonAlphanumeric(str3)); }} |
GeeksforGeeks123 GeeksforGeeks GeeksforGeeks123
Method 3: Using Regular Expression
Another approach involved using of regular expression. The string can be easily filtered using the ReGex [^a-zA-Z0-9 ].
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.


