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

Last updated by Dipen Dadhaniya on Dec 19, 2024 at 08:43 PM
| Reading Time: 3 minutes

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 (‘�’)

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

{

s = s.replace(c,’�’);

}

}

// 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: December 19, 2024
Register for our webinar

Uplevel your career with AI/ML/GenAI

Loading_icon
Loading...
1 Enter details
2 Select webinar slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Strange Tier-1 Neural “Power Patterns” Used By 20,013 FAANG Engineers To Ace Big Tech Interviews

100% Free — No credit card needed.

Register for our webinar

Uplevel your career with AI/ML/GenAI

Loading_icon
Loading...
1 Enter details
2 Select webinar slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

IK courses Recommended

Land high-paying DE jobs by enrolling in the most comprehensive DE Interview Prep Course taught by FAANG+ engineers.

Fast filling course!

Ace the toughest backend interviews with this focused & structured Backend Interview Prep course taught by FAANG+ engineers.

Elevate your engineering career with this interview prep program designed for software engineers with less than 3 years of experience.

Ready to Enroll?

Get your enrollment process started by registering for a Pre-enrollment Webinar with one of our Founders.

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC

Register for our webinar

How to Nail your next Technical Interview

Loading_icon
Loading...
1 Enter details
2 Select slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Almost there...
Share your details for a personalised FAANG career consultation!
Your preferred slot for consultation * Required
Get your Resume reviewed * Max size: 4MB
Only the top 2% make it—get your resume FAANG-ready!

Registration completed!

🗓️ Friday, 18th April, 6 PM

Your Webinar slot

Mornings, 8-10 AM

Our Program Advisor will call you at this time

Register for our webinar

Transform Your Tech Career with AI Excellence

Transform Your Tech Career with AI Excellence

Join 25,000+ tech professionals who’ve accelerated their careers with cutting-edge AI skills

25,000+ Professionals Trained

₹23 LPA Average Hike 60% Average Hike

600+ MAANG+ Instructors

Webinar Slot Blocked

Interview Kickstart Logo

Register for our webinar

Transform your tech career

Transform your tech career

Learn about hiring processes, interview strategies. Find the best course for you.

Loading_icon
Loading...
*Invalid Phone Number

Used to send reminder for webinar

By sharing your contact details, you agree to our privacy policy.
Choose a slot

Time Zone: Asia/Kolkata

Choose a slot

Time Zone: Asia/Kolkata

Build AI/ML Skills & Interview Readiness to Become a Top 1% Tech Pro

Hands-on AI/ML learning + interview prep to help you win

Switch to ML: Become an ML-powered Tech Pro

Explore your personalized path to AI/ML/Gen AI success

Your preferred slot for consultation * Required
Get your Resume reviewed * Max size: 4MB
Only the top 2% make it—get your resume FAANG-ready!
Registration completed!
🗓️ Friday, 18th April, 6 PM
Your Webinar slot
Mornings, 8-10 AM
Our Program Advisor will call you at this time

Get tech interview-ready to navigate a tough job market

Best suitable for: Software Professionals with 5+ years of exprerience
Register for our FREE Webinar

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC

Your PDF Is One Step Away!

The 11 Neural “Power Patterns” For Solving Any FAANG Interview Problem 12.5X Faster Than 99.8% OF Applicants

The 2 “Magic Questions” That Reveal Whether You’re Good Enough To Receive A Lucrative Big Tech Offer

The “Instant Income Multiplier” That 2-3X’s Your Current Tech Salary