Open In App

Program to check if a string contains any special character

Last Updated : 08 Apr, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Given a string, the task is to check if that string contains any special character (defined special character set). If any special character is 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 1: Using regular expression

  1. Make a regular expression(regex) object of all the special characters that we don’t want
  2. Then pass a string in the search method. 
  3. If any one character of the string is matching with the regex object 
  4. Then search method returns a match object otherwise returns 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
Java Python3 C# JavaScript PHP

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 Python3 C# JavaScript

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;
}
Java Python3 C# JavaScript

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.

Approach#4:using string.punctuation

Algorithm

1. Import the string module in Python, which contains a string called punctuation that includes all special characters.
2. Iterate through each character in the string.
3. Check if the character is in the punctuation string.
4. If a special character is found, print “String is not accepted”. Otherwise, print “String is accepted”.

import string

def check_string(s):
    for c in s:
        if c in string.punctuation:
            print("String is not accepted")
            return
    print("String is accepted")

# Example usage
check_string("Geeks$For$Geeks")  # Output: String is not accepted
check_string("Geeks For Geeks")  # Output: String is accepted

Output
String is not accepted
String is accepted

Time complexity: O(n), where n is the length of the input string. The loop iterates over each character in the string once.
Space complexity: O(1), as we are using only the string.punctuation string from the string module, which has a constant length.

METHOD 5:Using ASCII values

APPROACH:

The check_special_char_ascii function uses ASCII values to check if the input string contains any special characters. It iterates through each character in the string and checks if its ASCII value falls outside the range of alphabets and digits. If a special character is found, the function returns “String is not accepted.” Otherwise, it returns “String is accepted.”

ALGORITHM:

1. Initialize a for loop that iterates through each character in the input string.
2. For each character, check its ASCII value using the ord() function.
3. If the ASCII value falls outside the range of alphabets and digits, return “String is not accepted”.
4. If the loop completes without finding any special characters, return “String is accepted”.

C++
#include <iostream>
#include <string>

bool checkSpecialCharASCII(const std::string& str) {
    for (char c : str) {
        if (c < 48 || (c > 57 && c < 65) || (c > 90 && c < 97) || c > 122) {
            return false;
        }
    }
    return true;
}

int main() {
    std::string str = "Geeks$For$Geeks";
    if (checkSpecialCharASCII(str)) {
        std::cout << "String is accepted." << std::endl;
    } else {
        std::cout << "String is not accepted." << std::endl;
    }
    return 0;
}
Java Python3 C# JavaScript

Output
String is not accepted.

Time Complexity: The function iterates through each character in the string once, so the time complexity is O(n), where n is the length of the string.

Space Complexity: The function uses constant space, as it only creates a few variables to store the input string and the ASCII values of the characters. Therefore, the space complexity is O(1).



Next Article

Similar Reads

three90RightbarBannerImg