Java Program to Check Whether the String Consists of Special Characters

30 Mar, 2022
Special characters are those characters that are neither a letter nor a number. Whitespace is also not considered a special character. Examples of special characters are:- !(exclamation mark), , (comma), #(hash), etc. 
Methods:
Using Character classUsing regular expressions
Using Character class
Using regular expressions
Method 1: Using Character class
The approach is as follows:
Iterate through all the characters of the string.Alongside we will be checking each character for being a letter, a digit, or whitespace using the java character class.It is found to be none of the above signifying special characters.Parallelly we will maintain a counter for special character count.Lastly, print and display the required count or special characters as per the need.
Iterate through all the characters of the string.
Alongside we will be checking each character for being a letter, a digit, or whitespace using the java character class.
It is found to be none of the above signifying special characters.
Parallelly we will maintain a counter for special character count.
Lastly, print and display the required count or special characters as per the need.
Example
Java
// Java Program to Check Whether String contains Special// Characters Using Character Class // Importing input output classesimport java.io.*; // Main classclass GFG {     // Method 1    // Main driver method    public static void main(String[] args)    {        // Declaring and initializing count for        // special characters        int count = 0;         // Input custom string        String s            = "!#$GeeeksforGeeks.Computer.Science.Portal!!";         // Iterating through the string        // using standard length() method        for (int i = 0; i < s.length(); i++) {             // Checking the character for not being a            // letter,digit or space            if (!Character.isDigit(s.charAt(i))                && !Character.isLetter(s.charAt(i))                && !Character.isWhitespace(s.charAt(i))) {                // Incrementing the countr for spl                // characters by unity                count++;            }        }         // When there is no special character encounterd        if (count == 0)             // Display the print statement            System.out.println(                "No Special Characters found.");        else             // Special sharacter/s found then            // Display the print statement            System.out.println(                "String has Special Characters\n" + count + " "                + "Special Characters found.");    }}
String has Special Characters
8 Special Characters found.
Time Complexity: O(N)
Auxiliary Space: O(N) 
Method 2: Using regular expressions
Create a regular expression that does not match any letters, digits, or whitespace.We will use Matcher class in accordance with regular expression with our input string.Now, if there exist any ‘character matches’ with the regular expression then the string contains special characters otherwise it does not contain any special characters.Print the result.
Create a regular expression that does not match any letters, digits, or whitespace.
We will use Matcher class in accordance with regular expression with our input string.
Now, if there exist any ‘character matches’ with the regular expression then the string contains special characters otherwise it does not contain any special characters.
Print the result.
Java
// Java Program to Check Whether String contains Special// Characters using Regex classes // Importing regex classes from java.util package to// match a specific patternimport java.util.regex.Matcher;import java.util.regex.Pattern; // Main classpublic class GFG {    // Main driver method    public static void main(String[] args)    {        // Declaring and initializing strings randomly        // with input characters         // Custom Input as String 1        String s1 = "GeeksForGeeks";         // Creating regex pattern by        // creating object of Pattern class        Pattern p = Pattern.compile(            "[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);         // Creating matcher for above pattern on our string        Matcher m = p.matcher(s1);         // Now finding the matches for which        // let us set a boolean flag and        // imposing find() method        boolean res = m.find();         // Output will be based on boolean flag         // If special characters are found        if (res)             // Display this message on the console            System.out.println(                "String1 contains Special Characters");         // If we reach here means no special characters are        // found        else             // Display this message on the console            System.out.println(                "No Special Characters found in String 1");         // Custom Input as String 2        String s2 = "!!Geeks.For.Geeks##";         // Creating matcher for above pattern on our string        // by creating object of matcher class        Matcher m2 = p.matcher(s2);         // Finding the matches using find() method        boolean res2 = m2.find();         // If matches boolean returns true        if (res2)             // Then print and display thta special            // characters are found            System.out.println(                "String 2 contains Special Characters");         // If not        else             // Then Display the print statement below            System.out.println(                "No Special Characters found in String 2");    }}
No Special Characters found in String 1
String 2 contains Special Characters
 Time Complexity: O(N)
Auxiliary Space: O(N)
sagar0719kumar
rohitkumarsinghcna
Java-String-Programs
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array