Signup/Sign In

How To Remove Punctuation From String In Java

In this tutorial, we will learn how to remove punctuation from a String in Java. All the characters we enclosed in the square bracket are classified as punctuations [! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ ] ^ _ ` { | } ~ ]. These are basically part of grammar in any language. Java provides several ways to remove these from the String.

enlightenedRemoving punctuations is very simple using regular expressions considering str is a string below is the single line code for quick intuition.

str.replaceAll("\\p{Punct}", "");

Now, let's formally look towards the complete program of removing punctuations from a string.

Example of Removing Punctuatioins From String using replaceAll()

In the below code, we are calling replaceAll() method with regex expression that will find all the characters that are punctuation present in the string and it will replace with an empty string( "" ) which looks like punctuations are removed.

For more information, you can refer to this official documentation: Pattern (Java SE 14 & JDK 14 ) (oracle.com).

public class StudyTonight 
{ 
	public static void main(String[] args) 
	{ 
		String str = "?This String $% Contains$$ punctuation !!"; 
		str = str.replaceAll("\\p{Punct}",""); 
		System.out.println(str); 
	} 
} 


This String Contains punctuation

The regex expression is not a thing that comes very intuitively so, we will look at something which is very basic.

Example of Removing Punctuatioins From String using isLetterOrDigit() Method

In the below code first, we are converting a string to a character array using toCharArray() and then using isLetterOrDigit() whether the current character is a digit or an alphabet if so we will append it to the result string and it will form a new string.

public class StudyTonight 
{ 
	public static void main(String[] args) 
	{ 
		String str = "?This String $% Contains$$ punctuation !!"; 
		String res = "";
		for (Character c : str.toCharArray()) 
		{
			if(Character.isLetterOrDigit(c))
				res += c;
		}
		System.out.println(res); 
	} 
} 


ThisStringContainspunctuation

Conclusion:

In this article, we have learned to remove punctuations from a given string. It is a simple task with the combination of regex and Java methods like replaceAll() and isLetterOrDigit().



About the author:
I am a 3rd-year Computer Science Engineering student at Vellore Institute of Technology. I like to play around with new technologies and love to code.