Skip to content
Related Articles
Open in App
Not now

Related Articles

Program to check if a string contains any special character

Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 21 Mar, 2023
Improve Article
Save Article

Given a string, the task is to check if that string contains any special character (defined special character set). If any special character found, don’t accept that string.
Examples : 

Input : Geeks$For$Geeks
Output : String is not accepted.

Input : Geeks For Geeks
Output : String is accepted

Approach: Make a regular expression(regex) object of all the special characters that we don’t want, then pass a string in search method. If any one character of string is matching with regex object then search method returns a match object otherwise return None.
Below is the implementation : 
 

C++




// C++ program to check if a string
// contains any special character
 
// import required packages
#include <iostream>
#include <regex>
using namespace std;
 
// Function checks if the string
// contains any special character
void run(string str)
{
     
    // Make own character set
    regex regx("[@_!#$%^&*()<>?/|}{~:]");
 
    // Pass the string in regex_search
    // method
    if(regex_search(str, regx) == 0)
        cout << "String is accepted";
    else
        cout << "String is not accepted.";
}
 
// Driver Code
int main()
{
     
    // Enter the string
    string str = "Geeks$For$Geeks";
     
    // Calling run function
    run(str);
 
    return 0;
}
 
// This code is contributed by Yash_R

Python3




# Python3 program to check if a string
# contains any special character
 
# import required package
import re
 
# Function checks if the string
# contains any special character
def run(string):
 
    # Make own character set and pass
    # this as argument in compile method
    regex = re.compile('[@_!#$%^&*()<>?/\|}{~:]')
     
    # Pass the string in search
    # method of regex object.   
    if(regex.search(string) == None):
        print("String is accepted")
         
    else:
        print("String is not accepted.")
     
 
# Driver Code
if __name__ == '__main__' :
     
    # Enter the string
    string = "Geeks$For$Geeks"
     
    # calling run function
    run(string)

PHP




<?Php
// PHP program to check if a string
// contains any special character
 
// Function checks if the string
// contains any special character
function run($string)
{
    $regex = preg_match('[@_!#$%^&*()<>?/\|}{~:]',
                                         $string);
    if($regex)
        print("String is accepted");
         
    else
        print("String is not accepted.");
}
 
// Driver Code
 
// Enter the string
$string = 'Geeks$For$Geeks';
 
// calling run function
run($string);
 
// This code is contributed by Aman ojha
?>

Java




import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class Main {
    public static void main(String[] args)
    {
        String str = "Geeks$For$Geeks";
        Pattern pattern
            = Pattern.compile("[@_!#$%^&*()<>?/|}{~:]");
        Matcher matcher = pattern.matcher(str);
 
        if (!matcher.find()) {
            System.out.println("String is accepted");
        }
        else {
            System.out.println("String is not accepted");
        }
    }
}// this code is contributed by devendrasalunke

C#




// C# program to check if a string
// contains any special character
 
using System;
using System.Text.RegularExpressions;
 
class Program {
    // Function checks if the string
    // contains any special character
    static void Run(string str)
    {
        // Make own character set
        Regex regex = new Regex("[@_!#$%^&*()<>?/|}{~:]");
        // Pass the string in regex.IsMatch
        // method
        if (!regex.IsMatch(str))
            Console.WriteLine("String is accepted");
        else
            Console.WriteLine("String is not accepted.");
    }
 
    // Driver Code
    static void Main()
    {
        // Enter the string
        string str = "Geeks$For$Geeks";
 
        // Calling Run function
        Run(str);
 
        Console.ReadLine();
    }
}

Output

String is not accepted.

Method:  To check if a special character is present in a given string or not, firstly group all special characters as one set. Then using for loop and if statements check for special characters. If any special character is found then increment the value of c. Finally, check if the c value is greater than zero then print string is not accepted otherwise print string is accepted. 

C++




// C++ code
// to check if any special character is present
// in a given string or not
#include <iostream>
#include <string>
using namespace std;
 
int main() {
 
  // Input string
  string n = "Geeks$For$Geeks";
  int c = 0;
  string s = "[@_!#$%^&*()<>?}{~:]"; // special character set
  for(int i = 0; i < n.size(); i++)
  {
     
    // checking if any special character is present in given string or not
    if (s.find(n[i]) != string::npos )
    {
      // if special character found then add 1 to the c
      c++;
    }
  }
   
   // if c value is greater than 0 then print no
// means special character is found in string 
  if(c){
    cout << "string is not accepted" ;
  }
  else{
    cout << "string is accepted";
  }
    
    return 0;
}
 
// This code is contributed by uomkar369.

Java




// Java code to check if any special character is present
// in a given string or not
import java.util.*;
class Main {
    public static void main(String[] args)
    {
        // Input string
        String n = "Geeks$For$Geeks";
        int c = 0;
        String s = "[@_!#$%^&*()<>?}{~:]"; // special
                                           // character set
        for (int i = 0; i < n.length(); i++) {
 
            // checking if any special character is present
            // in given string or not
            if (s.indexOf(n.charAt(i)) != -1) {
                // if special character found then add 1 to
                // the c
                c++;
            }
        }
 
        // if c value is greater than 0 then print no
        // means special character is found in string
        if (c > 0) {
            System.out.println("string is not accepted");
        }
        else {
            System.out.println("string is accepted");
        }
    }
}

Python3




# Python code
# to check if any special character is present
#in a given string or not
 
# input string
n="Geeks$For$Geeks"
n.split()
c=0
s='[@_!#$%^&*()<>?/\|}{~:]' # special character set
for i in range(len(n)):
    # checking if any special character is present in given string or not
    if n[i] in s:
      c+=1   # if special character found then add 1 to the c
 
# if c value is greater than 0 then print no
# means special character is found in string     
if c:
    print("string is not accepted")
else:
    print("string accepted")
 
# this code is contributed by gangarajula laxmi

Javascript




// JavaScript code
// to check if any special character is present
// in a given string or not
const n = "Geeks$For$Geeks";
let c = 0;
const s = "[@_!#$%^&*()<>?}{~:]"; // special character set
 
for (let i = 0; i < n.length; i++) {
    // checking if any special character is present in given string or not
    if (s.includes(n[i])) {
        // if special character found then add 1 to the c
        c++;
    }
}
 
// if c value is greater than 0 then print no
// means special character is found in string
if (c) {
    console.log("string is not accepted");
} else {
    console.log("string is accepted");
}

Output

string is not accepted

 Using inbuilt methods:

Here is another approach to checking if a string contains any special characters without using regular expressions:

C++




#include <iostream>
#include <string>
 
using namespace std;
 
bool hasSpecialChar(string s) {
    for (char c : s) {
        if (!(isalpha(c) || isdigit(c) || c == ' ')) {
            return true;
        }
    }
    return false;
}
 
int main() {
    string s = "Hello World";
    if (hasSpecialChar(s)) {
        cout << "The string contains special characters." << endl;
    } else {
        cout << "The string does not contain special characters." << endl;
    }
 
    s = "Hello@World";
    if (hasSpecialChar(s)) {
        cout << "The string contains special characters." << endl;
    } else {
        cout << "The string does not contain special characters." << endl;
    }
 
    return 0;
}

Python3




def has_special_char(s):
  for c in s:
    if not (c.isalpha() or c.isdigit() or c == ' '):
      return True
  return False
 
# Test the function
s = "Hello World"
if has_special_char(s):
  print("The string contains special characters.")
else:
  print("The string does not contain special characters.")
 
s = "Hello@World"
if has_special_char(s):
  print("The string contains special characters.")
else:
  print("The string does not contain special characters.")
#This code is contributed by Edula Vinay Kumar Reddy

Java




class Main {
    public static boolean hasSpecialChar(String s)
    {
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (!(Character.isLetterOrDigit(c)
                  || c == ' ')) {
                return true;
            }
        }
        return false;
    }
 
    public static void main(String[] args)
    {
        String s1 = "Hello World";
        if (hasSpecialChar(s1)) {
            System.out.println(
                "The string contains special characters.");
        }
        else {
            System.out.println(
                "The string does not contain special characters.");
        }
        String s2 = "Hello@World";
        if (hasSpecialChar(s2)) {
            System.out.println(
                "The string contains special characters.");
        }
        else {
            System.out.println(
                "The string does not contain special characters.");
        }
    }
}

Output

The string does not contain special characters.
The string contains special characters.

This approach uses the isalpha() and isdigit() methods to check if a character is an alphabetical character or a digit, respectively. If a character is neither an alphabetical character nor a digit, it is considered a special character.

The time complexity of this function is O(n), where n is the length of the input string, because it involves a single loop that iterates through all the characters in the string.

The space complexity of this function is O(1), because it does not use any additional data structures and the space it uses is independent of the input size.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!