How to remove Special Characters from a String in Java

In this tutorial, you will learn how to remove special characters from a String in Java.

Let’s first define what a special character is.

A special character is a character which neither alphabetic nor numeric. Here, we will remove all these special characters to read the string clearly and fluently.

There are two methods by which we can perform this task:

         01: By using replaceAll() function and regular expression.

         02: Simply Loop through the String and create a new String where only alphabets and numeric values will be added.

Method 01: Using Regular Expression and replaceAll() in Java

In this method the replaceAll() function takes two arguments :

  • Regex: The regular expression for which the string has to be matched
  • Replacement: The string which replaces the special character

Lets Code for a certain String :

import java.io.*;
class Solution{
    public static void main(String[] args)throws IOException{
        BufferedReader in =new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter a String \n");
        String x=in.readLine();
        x=x.replaceAll("[^a-zA-Z0-9]", "");
        System.out.println(x);
    }
}

OUTPUT:

Enter a String

Hello&my$name$is&Subhojeet*Ghosh

HellomynameisSubhojeetGhosh

In this output, as you can see the regex written in the program states that any character other than A-Z, a-z, or 0-9  gets removed. This means special character gets replaced by nothings which automatically removes them.

Method 2: Loop through the String and Remove the Special character

CODE:

import java.io.*;
class Solution{
    public static void main(String[] args)throws IOException{
        BufferedReader in =new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter a String \n");
        String x=in.readLine();
        String newstr="";
        for(int i=0;i<x.length();i++){
            if (x.charAt(i)>64 && x.charAt(i)<=122)
            {  
            newstr=newstr+x.charAt(i);  
            }  
    }
    System.out.println(newstr);
}
}

OUTPUT:

Enter a String

Jav$a is$ Co%%$ol

JavaisCool

In this output with the help of loops, special characters are removed with O(n) Complexity.

I hope you like our content. Happy Coding.

Leave a Reply

Your email address will not be published.