Register for our webinar

How to Nail your next Technical Interview

1 hour
Loading...
1
Enter details
2
Select webinar slot
*Invalid Name
*Invalid Name
By sharing your contact details, you agree to our privacy policy.
Step 1
Step 2
Congratulations!
You have registered for our webinar
check-mark
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
*All webinar slots are in the Asia/Kolkata timezone
Step 1
Step 2
check-mark
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.
close-icon
Iks white logo

You may be missing out on a 66.5% salary hike*

Nick Camilleri

Head of Career Skills Development & Coaching
*Based on past data of successful IK students
Iks white logo
Help us know you better!

How many years of coding experience do you have?

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Iks white logo

FREE course on 'Sorting Algorithms' by Omkar Deshpande (Stanford PhD, Head of Curriculum, IK)

Thank you! Please check your inbox for the course details.
Oops! Something went wrong while submitting the form.
Our June 2021 cohorts are filling up quickly. Join our free webinar to Uplevel your career
close
closeAbout usWhy usInstructorsReviewsCostFAQContactBlogRegister for Webinar

How to Remove All Non-alphanumeric Characters From a String in Java?

Last updated by Dipen Dadhaniya on Sep 25, 2024 at 10:59 PM | Reading time: 6 minutes

The fast well prepared banner

Attend our Free Webinar on How to Nail Your Next Technical Interview

WEBINAR +LIVE Q&A

How To Nail Your Next Tech Interview

How to Remove All Non-alphanumeric Characters From a String in Java?
Hosted By
Ryan Valles
Founder, Interview Kickstart
strategy
Our tried & tested strategy for cracking interviews
prepare list
How FAANG hiring process works
hiring process
The 4 areas you must prepare for
hiring managers
How you can accelerate your learnings

Given: A string containing some ASCII characters.

Task: To remove all non-alphanumeric characters in the given string and print the modified string. 

In this article, we’ll explore:

  • What are Alphanumeric and Non-alphanumeric Characters?
  • How to Remove Non-alphanumeric Characters in Java:
    Method 1: Using ASCII values
    Method 2: Using String.replace()
    Method 3: Using String.replaceAll() and Regular Expression

What Are Alphanumeric and Non-alphanumeric Characters? 

Alpha stands for alphabets, and numeric stands for a number. So, alphabets and numbers are alphanumeric characters, and the rest are non-alphanumeric.

Examples of alphanumeric characters: ‘a’, ‘A’, ‘p’, ‘2’

Examples of non-alphanumeric characters: ‘!’, ‘{‘, ‘&’ 

Examples

  • Example 1:

Input: Interview!@Kickstart23

Output: InterviewKickstart23

Here the symbols ‘!’ and ‘@’ are non-alphanumeric, so we removed them. 

  • Example 2:

Input: Interview_{@Kick}start

Output: InterviewKickstart

Here the symbols ‘_’, ‘{’, ‘}’ and ‘@’ are non-alphanumeric, so we removed them. 

  • Example 3:

Input: InterviewKickstart23

Output: InterviewKickstart23

Here, there’s no need to remove any characters because all of them are alphanumeric. 

How to Remove Non-alphanumeric Characters in Java?

To remove non-alphanumeric characters in a given string in Java, we have three methods; let’s see them one by one. 

Method 1: Using ASCII values

If we see the ASCII table, characters from ‘a’ to ‘z’ lie in the range 65 to 90. Characters from ‘A’ to ‘Z’ lie in the range 97 to 122, and digits from ‘0’ to ‘9’ lie in the range 48 to 57.

Thus, we can differentiate between alphanumeric and non-alphanumeric characters by their ASCII values. 

In this method, we’ll make an empty string object, traverse our input string and fetch the ASCII value of each character. If the ASCII value is in the above ranges, we append that character to our empty string. Else, we move to the next character.

After iterating over the string, we update our string to the new string we created earlier. 

Code:

/*

  Java program to remove non-alphanumeric characters with 

  Method 1: Using ASCII values

*/

public class Main {

  

    // Function to remove the non-alphanumeric characters and print the resultant string

    public static String rmvNonalphnum(String s)

    {

        String temp = "";

         for(int i=0;i<s.length();i++) 

         {

             // current character

             char c = s.charAt(i);

             

             // get the ascii value of current character

             int ascii = (int)c;

             

             // check if the ascii value in our ranges of alphanumeric and if yes then print the character

             if((ascii>=65 && ascii<=90) || (ascii>=97 && ascii<=122) || (ascii>=48 && ascii<=57)) 

             {

                 temp+=c;

             }

            

         }

         return temp;

    }

  

    // Driver Code

    public static void main(String args[])

    {

        // Test Case 1:

        String s1  = "Interview!@Kickstart23";

        // calling the function

        s1 = rmvNonalphnum(s1);

        System.out.println(s1);

        

        // Test Case 2:

        String s2 = "Interview_{@Kick}start";

        // calling the function

        s2 = rmvNonalphnum(s2);

        System.out.println(s2);

        

        // Test Case 3:

        String s3  = "InterviewKickstart23";

        // calling the function

        s3 = rmvNonalphnum(s3);  

        System.out.println(s3);

    }

}

Method 2: Using String.replace() 

In this approach, we use the replace() method in the Java String class. We use this method to replace all occurrences of a particular character with some new character.

About String.replace()

  • Syntax:

                       public String replace(char a, char b)

  • Parameters:

                      a: old character that we need to replace.

                      b: new character which needs to replace the old character.

  • Return Value:

                       Resultant string after replacements.

In this approach, we loop over the string and find whether the current character is non-alphanumeric or not using its ASCII value (as we have already done in the last method). If it is non-alphanumeric, we replace all its occurrences with empty characters using the String.replace() method.  

Code:

/*

  Java program to remove non-alphanumeric characters with 

  Method 2: Using String.replace() 

*/

public class Main {

  

    // Function to remove the non-alphanumeric characters and print the resultant string

    public static String rmvNonalphnum(String s)

    {

         for(int i=0;i<s.length();i++) 

         {

             // current character

             char c = s.charAt(i);

             

             // get the ascii value of current character

             int ascii = (int)c;

             

             // check if the current character is non-alphanumeric if yes then replace it's all occurrences with empty char ('\0')

             if(!((ascii>=65 && ascii<=90) || (ascii>=97 && ascii<=122) || (ascii>=48 && ascii<=57))) 

             {

                s = s.replace(c,'\0');

             }

         }

         // returning the resultant string

         return s;

    }

  

    // Driver Code

    public static void main(String args[])

    {

        // Test Case 1:

        String s1  = "Interview!@Kickstart23";

        // calling the function

        s1 = rmvNonalphnum(s1);

        System.out.println(s1);

        

        // Test Case 1:

        String s2 = "Interview_{@Kick}start";

        // calling the function

        s2 = rmvNonalphnum(s2);

        System.out.println(s2);

        

        // Test Case 1:

        String s3  = "InterviewKickstart23";

        // calling the function

        s3 = rmvNonalphnum(s3);  

        System.out.println(s3);

    }

}

Method 3: Using String.replaceAll() and Regular Expression 

In this approach, we use the replaceAll() method in the Java String class. This method returns the string after replacing each substring that matches a given regular expression with a given replace string.

About String.replaceAll()

  • Syntax:

                       public String replaceAll(String rgx, String replaceStr)

  • Parameters:

          replaceStr: the string which would replace the found expression.

                      rgx: the regular expression that this string needs to match.

  • Return Value

                     Resultant string after replacements.

So, we use this method to replace the non-alphanumeric characters with an empty string. 

  • Our regular expression will be: [^a-zA-Z0-9]. This means, “only consider pattern substring with characters ranging from ‘a’ to ‘z’, ‘A’ to ‘Z’ and ‘0’ to ‘9’.”
  • Replacement String will be: "" (empty string) 
  • Here ^ Matches the beginning of the input: It means, “replace all substrings with pattern [^a-zA-Z0-9] with the empty string.”

Code:

/*

  Java program to remove non-alphanumeric characters with 

  Method 2: Using String.replace() 

*/

public class Main {

  

    // Function to remove the non-alphanumeric characters and print the resultant string

    public static void rmvNonalphnum(String s)

    {

        // replacing all substring patterns of non-alphanumeric characters with empty string

        s = s.replaceAll("[^a-zA-Z0-9]", "");

         

    }

  

    // Driver Code

    public static void main(String args[])

    {

        // Test Case 1:

        String s1  = "Interview!@Kickstart23";

        // calling the function

        rmvNonalphnum(s1);

        System.out.println(s1);

        

        // Test Case 1:

        String s2 = "Interview_{@Kick}start";

        // calling the function

        rmvNonalphnum(s2);

        System.out.println(s2);

        

        // Test Case 1:

        String s3  = "InterviewKickstart23";

        // calling the function

        rmvNonalphnum(s3);  

        System.out.println(s3);

    }

}

Are You Ready to Nail Your Next Coding Interview?

Whether you’re a Coding Engineer gunning for Software Developer or Software Engineer roles, or you’re targeting management positions at top companies, IK offers courses specifically designed for your needs to help you with your technical interview preparation!

If you’re looking for guidance and help with getting started, sign up for our free webinar. As pioneers in the field of technical interview prep, we have trained thousands of Software Engineers to crack the most challenging coding interviews and land jobs at their dream companies, such as Google, Facebook, Apple, Netflix, Amazon, and more!

Sign up now!

————

Article contributed by Omkar Deshmukh

 




Last updated on: 
November 20, 2024
Author

Dipen Dadhaniya

Engineering Manager at Interview Kickstart

Attend our Free Webinar on How to Nail Your Next Technical Interview

Register for our webinar

How to Nail your next Technical Interview

1
Enter details
2
Select webinar slot
First Name Required*
Last Name Required*
By sharing your contact details, you agree to our privacy policy.
Step 1
Step 2
Congratulations!
You have registered for our webinar
check-mark
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
Step 1
Step 2
check-mark
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.

How to Remove All Non-alphanumeric Characters From a String in Java?

Worried About Failing Tech Interviews?

Attend our webinar on
"How to nail your next tech interview" and learn

Ryan-image
Hosted By
Ryan Valles
Founder, Interview Kickstart
blue tick
Our tried & tested strategy for cracking interviews
blue tick
How FAANG hiring process works
blue tick
The 4 areas you must prepare for
blue tick
How you can accelerate your learnings
Register for Webinar
entroll-image