In this tutorial, we will learn how to remove special characters from a string in java. For example, if the given string is “Hello @ World” then the output will be “Hello World”.
In order to remove special characters, we can use regex along with the replaceAll()
method.
Java Program to remove special characters from a String
public class RemoveSpecialCharacters {
public static void main(String[] args) {
//given string
String input = "Hello! How are you? #Good -morning!";
//calling the user defined method for removing special chars
String result = removeSpecialCharacters(input);
System.out.println("Original: " + input);
System.out.println("After removing special characters: " + result);
}
public static String removeSpecialCharacters(String str) {
// This regular expression matches all special characters
//[^a-zA-Z0-9\\s]
matches any character that is not an
// uppercase letter, lowercase letter, digit, or whitespace.
String regex = "[^a-zA-Z0-9\\s]";
// Replace all special characters with an empty string
// Note: There is no space between double quotes
return str.replaceAll(regex, "");
}
}
Output
Original: Hello! How are you? #Good -morning!
After removing special characters: Hello How are you Good morning
Points to Note:
- You can adjust the regular expression to match specific types of special characters based on your requirements. Refer regex tutorial.
- If you want to remove whitespace from the string, you can use
trim()
method. Refer: trim() method and remove whitespace from string.
Leave a Reply