Problem: Write a Java program to check whether a given string contains a special character or not.
Example:
Input: pencil@programmer Output: String has Special Character Input: Pencil Programmer Output: String has No Special Character
So let’s see how we can do that in Java.
Method 1: Using Java Regex
The Java Regex or regular expression is a pattern (sequence of characters) that helps in the search or manipulation of strings.
We usually define a regex pattern in the form of a string, for example “[^A-Za-z0-9 ]” and use a matcher in Java to match the pattern in a particular string.
“[A-Za-z0-9 ]” will match strings made up of alphanumeric characters only (blank space inclusive).
“[^A-Za-z0-9 ]” will match strings made up of characters other than alphanumeric and blank spaces i.e. special characters.
So if the input string matches the “[^A-Za-z0-9 ]” pattern it means it contains at least one character.
Let’s implement the same in Java and check whether a string contains a special character or not:
//import Pattern and Matcher classes from java.util package
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("Enter a String");
String str = in.nextLine();
//Specify the pattern and get matcher
Pattern p = Pattern.compile("[^A-Za-z0-9 ]");
Matcher m = p.matcher(str);
if(m.find())
System.out.println("String contains Special Characters");
else
System.out.println("String doesn't have any Special Characters");
}
}
Output:
Note: The [^A-Za-z0-9]
pattern will return true if a string contains a blank space, therefore we have modified the pattern to [^A-Za-z0-9 ]
to exclude the blank space from the check criteria.
Method 2: Using Brute Force
In this method, we specify all possible special characters into a single string, then match each of them in the input string.
For this, we use the inbuilt contain()
method of string class.
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("Enter a String");
String str = in.nextLine();
//Specify all posible special charcters
String specialCharacters=" !#$%&'()*+,-./:;<=>?@[]^_`{|}";
boolean found = false;
for(int i=0; i<specialCharacters.length(); i++){
//Checking if the input string contain any of the specified Characters
if(str.contains(Character.toString(specialCharacters.charAt(i)))){
found = true;
System.out.println("String contains Special Characters");
break;
}
}
if(found == false)
System.out.println("String doesn't have any Special Characters");
}
}
Output:
These are the two methods using which we can easily check for special characters in the Java string.