×

How to remove special characters from String in Java

Strings in Java are Objects that are supported inside by a burn exhibit. Since exhibits are immutable (cannot develop), Strings are changeless too. A completely new String is made whenever a change to a String is made.

Syntax: 

<String_Type>    <string_variable> = "<sequence_of_strings>";

Java String class gives a ton of strategies to perform procedure on strings like compare(), concat(), rises to(), split(), length(), split(), compareTo(), intern(), substring() and so on.

There are two methods for making String objects:

  • String literal
  • New keyword

1. String Literal: Java String literal is made by utilizing twofold statements.

Example: String s = "Victory"; 

2. New Keyword: The new keyword is used for creating the string.

Example: String s=new String("Victory");

replaceAll() method

A character, which isn't a letter set or numeric character is known as a unique character. We ought to eliminate every one of the exceptional characters from the string with the goal that we can peruse the string plainly and easily. Unique characters are not lucid, so eliminating them prior to reading would be great.

Java replaceAll() strategy for String class replaces every substring of this string that coordinates the given ordinary articulation with the substitution.

Syntax:

Public String replaceAll(String regex, String replacement) 

You can utilize a standard articulation and replaceAll() technique for java.lang.String class to eliminate all exceptional characters from a string. An extraordinary person is only characters like - ! #, %, and so on. Exactly, you want to characterize what is an exceptional person for you. When you characterize that, you can utilize a normal articulation to supplant those characters with a void String, which is identical to eliminating all extraordinary characters from a string.

For instance, assume your string contains a few extraordinary characters, like "Awesome!!!" and you need to eliminate symbols,!!! To decrease some energy, you can utilize replaceAll("!", "") to dispose of all interjection marks from the string. Also, in the event that your string contains numerous extraordinary characters, you can eliminate every one of them simply with the help of picking alphanumeric characters, for example,  replaceAll("[^a-zA-Z0-9_-]", "), which will supplant anything with void string aside from a to z, a to z, 0 to 9,_ and dash. This technique acknowledges two boundaries:

Regex: It is the ordinary articulation to which string is to be coordinated. It could be of various sorts.

Replacement: The string to be filled in for the match.

The Java Regex or Regular Expression is an API to characterize an example for looking at or controlling strings. It is broadly used to characterize the limitation on strings like secret phrases and email approval. In the wake of learning the Java regex instructional exercise, you will actually want to test your normal articulations with the Java Regex Tester Tool. Java Regex API gives one interface and three classes in java.util.regex bundle. The Matcher and Pattern classes give the office of Java normal articulation. The java.util.regex bundle gives the following classes and connection points to standard articulations.

  • MatchResult interface
  • Matcher class
  • Pattern class
  • PatternSyntaxException class

Matcher class

It executes the MatchResult interface. It is a regex motor which is utilized to perform a matching procedure on a person's succession.

  • boolean matches(): Test whether the ordinary articulation matches the example.
  • boolean find(): Finds the following articulation that matches the example.
  • boolean find(int start): Finds the following articulation that matches the example from the given beginning number.
  • String group(): Returns the matched aftereffect.
  • int start(): Returns the beginning list of the matched aftereffect.
  • int end(): Returns the closure record of the matched aftereffect.
  • int group count(): Returns the all-out number of the matched aftereffect.

Pattern class

It is the incorporated variant of a standard articulation. It is utilized to characterize an example of the regex engine.

  • Static Pattern compile(String regex): Incorporates the given regex and returns the occurrence of the Pattern.
  • Matcher matcher(CharSequence input): Itmakes a matcher that coordinates the given contribution with the example.
  • static boolean matches(String regex, CharSequence input): It fills in as the blend of arranging and matcher strategies. It assembles the customary articulation and coordinates the given contribution with the example.
String[] split(CharSequence input)

How does the replaceAll() method work in java

replaceAll is the strategy that is available in the String class. It accepts two boundaries as info, for example, customary articulation and substitution. As the name proposes, supplanting some piece of a string or the entire string is utilized.

This strategy tosses the exemption referenced underneath:

1. PatternSyntaxException: This exemption is the uncontrolled special case in java which will possibly happen on the off chance that there is a blunder in the standard articulation we pass in the technique as the information boundary.

2. Regular expression detail: The regular expression that we are passing as a string into the strategy boundary, yet this normal articulation is the example of class' ordered occurrence. it is available in java.util.regex.Pattern bundle.

3. Strategies accessible: Split (CharSequence input): This strategy returns us string [] (string exhibit) and takes input for the benefit of we need to part. Split (CharSequence input, int limit): works similarly, yet this technique likewise takes a breaking point boundary. Static Pattern compile(String regex, int flags): This strategy takes two boundaries, standard articulation and banner and aggregates our customary articulation.

4. String pattern()

5. static String quote(String s)

Example

public class RemoveSpecialCharacterEx1  
{  
public static void main(String args[])   
{  
String s= "Hello#world%^Welcome*&.";   
s = s.replaceAll("[^a-zA-Z0-9]", " ");  
System.out.println(s);  
}  
}  

Output:

Hello world  Welcome

In the accompanying model, the removeAll() strategy eliminates every one of the extraordinary characters from the string and sets up a space for them.

Removing Special Characters Using User-Defined Logic

In the accompanying model, we are characterizing the rationale to eliminate exceptional characters from a string. We realize that the ASCII worth of capital letter in order begins from 65 to 90 (A-Z), and the ASCII worth of little letter set begins from 97 to 122 (a-z). Each character contrast and their comparing ASCII esteem.

Assuming that both the predefined condition returns genuine, it returns genuine else get back misleading. The for circle executes till the length of the string. While the string arrives at its size, it ends execution, and we get the resultant string.

Example

public class RemoveUserDefinedSpecialCharacter 
{  
public static void main(String[] args)   
{  
//declaring a string having special characters   
String str="Pr!ogr#am%m*in&g Lan?#guag(e";  
String resultStr="";  
//loop execute till the end of the string   
for (int i=0;i<str.length();i++)  
{  
//comparing alphabets with their corresponding ASCII value  
if (str.charAt(i)>64 && str.charAt(i)<=122) //returns true if both conditions are true  
{   
resultStr=resultStr+str.charAt(i);  
}  
}  
System.out.println("String after removal of special characters: "+resultStr);  
}  
}  

Output:

String after removal of special characters: ProgrammingLanguage

Related Topics

Java Enumeration

In a computer language, enumerations express a set of named constants. For instance, the four suits in a deck of playing cards could be represented by the enumerators Club, Diamond,...

4 minutes read.

Java Get Time in UTC

UTC is the abbreviation for Universal Time Coordinated. Before the beginning of UTC, it is mentioned as the Greenwich Mean Time (GMT) but Now it is mentioned as the universal...

4 minutes read.

Java Serialization

JAVA SERIALIZATION Serialization is a process by which objects can be represented as a sequence of bytes. These bytes have information about object's data, object's type and datatypes of members in...

3 minutes read.

Java StringBuffer vs StringBuilder

Java StringBuffer vs StringBuilder StringBuffer The StringBuffer class is used to create mutable string. StringBuffer shows writable and growable character sequences. Java StringBuffer program FileName: StringBufferExample.java // A basic program that demonstrates the working...

2 minutes read.

Java Volatile Keyword

The compiler, runtime, or processors may use any kind of optimization if there aren't any required synchronizations. Although most of the time these improvements are advantageous, they occasionally can result...

6 minutes read.

Knapsack problem in Java

We have a collection of items in the knapsack problem. Every object has a weight and a value. These things should go in a knapsack. But there is a weight...

3 minutes read.

Java Get File Size

There are three ways to get the file size in Java. Using Java InputOutput Using NewInputOutput Library Files.size() Method FileChannel.size() Method Using Apache Commons InputOutput Using Java InputOutput: The Java IO package offers the classes that deal...

5 minutes read.

Split String into String Array in Java

The String split() technique returns a variety of divided strings after the strategy parts the given String around matches of a given normal articulation containing the delimiters. The ordinary articulation...

4 minutes read.

Bouncy Number in Java

We will define bouncy numbers in this section and write Java programmes to determine whether a specific number is bouncy. Java coding exams and academic assignments usually inquire about the...

3 minutes read.

Concurrent Modification Exception In Java

When an object is attempted to be updated concurrently when it is not allowed, the ConcurrentModificationException arises. This error typically occurs while using Java Collection classes. When another thread is iterating...

5 minutes read.

How to Read CSV Files in Java?

Comma-Separated Values is the acronym for this format. It is a straightforward file format storing textual tabular data in a database or spreadsheet. The CSV files can be imported into...

3 minutes read.

How to write basic Java Programs

Java Basic Programs In this section, we will learn how to write basic Java programs. But first we need to take care of the following requirement list. To execute a Java program,...

4 minutes read.

Java Read File to String

There are different ways to deal with forming and examining a text record. This is normal while dealing with various applications. There are different ways to deal with looking at a...

6 minutes read.

Java Boolean logicalOr() Method

The logicalOr() method of Java Boolean class returns the result of implementing logical OR operation on the specified Boolean operands. Syntax: public static boolean logicalOr (boolean a, boolean b) Parameters: The parameters ‘a’ and...

2 minutes read.

Java Database Connectivity with Oracle

JDBC: A Programmer can develop a complete application using the Java built-in API’s. So, for storing the data required for solving a real-world problem is stored into a database. To connect...

5 minutes read.

Method and Block Synchronization in Java

The Synchronization is performed in multi-threading concept. The multi-threading is a concept of parallel running of a program for the execution. In the multi-threading concept, the threads are run by...

3 minutes read.

Fall through in Java

In this article, you will be acknowledged about the fall through condition in Java along with an example program. Fall through It is a situation where there isn't a break statement in...

3 minutes read.

Java time local date

Java: Java is one of the programming language which is object oriented. It consists of many features such as robust, simple, architecture neutral, dynamic, distributed, multi threaded, portable etc. The main feature...

3 minutes read.

Java Char Keyword

The java char keyword is a data type which is defined as character data type.Char keyword belongs to a primitive data type where the data types are classified into primitive...

4 minutes read.

How to check if date is valid in Java?

In this article, you will acknowledge about how to verify if a date is valid or not. For this you will learn the approach, you will be able to write...

3 minutes read.