Java Program to Check Whether the String Consists of Special Characters

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 class
- Using regular expressions
- Using contains() method
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.
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 encountered        if (count == 0)Â
            // Display the print statement            System.out.println(                "No Special Characters found.");        elseÂ
            // Special character/s found then            // Display the print statement            System.out.println(                "String has Special Characters\n" + count + " "                + "Special Characters found.");    }} |
Output
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.
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 that 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");    }} |
Output
No Special Characters found in String 1 String 2 contains Special Characters
 Time Complexity: O(N)
Auxiliary Space: O(N)
Method 3 : Using contains() method
Java
// Java Program to Check Whether String contains Special Charactersimport java.io.*;import java.util.*;// Main classclass Main{Â
    // Method 1    // Main driver method    public static void main(String[] args)    {        // Declaring and initializing count for        // special characters        int count = 0;                 ArrayList<Character> a = new ArrayList<Character>();        String b="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";        for(int i=0;i<b.length();i++)        {            a.add(b.charAt(i));                     }        // 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 (!a.contains(s.charAt(i)) && !Character.isWhitespace(s.charAt(i))) {                // Incrementing the countr for spl                // characters by unity                count++;            }        }Â
        // When there is no special character encountered        if (count == 0)            // Display the print statement            System.out.println("No Special Characters found.");        elseÂ
            // Special character/s found then            // Display the print statement            System.out.println("String has Special Characters\n" + count + " "+ "Special Characters found.");    }} |
Output
String has Special Characters 8 Special Characters found.



