Friday, December 27, 2024
Google search engine
HomeLanguagesJavaJava Program to Check Whether the String Consists of Special Characters

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:

  1. Using Character class
  2. Using regular expressions
  3. Using contains() method

Method 1: Using Character class

The approach is as follows:

  1. Iterate through all the characters of the string.
  2. Alongside we will be checking each character for being a letter, a digit, or whitespace using the java character class.
  3. It is found to be none of the above signifying special characters.
  4. Parallelly we will maintain a counter for special character count.
  5. 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 classes
import java.io.*;
 
// Main class
class 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

  1. Create a regular expression that does not match any letters, digits, or whitespace.
  2. We will use Matcher class in accordance with regular expression with our input string.
  3. 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.
  4. 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 pattern
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
// Main class
public 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 Characters
import java.io.*;
import java.util.*;
// Main class
class 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.
RELATED ARTICLES

Most Popular

Recent Comments