Program to check if a string contains any special character
Last Updated :
08 Apr, 2024
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
- Make a regular expression(regex) object of all the special characters that we don't want
- Then pass a string in the search method.
- If any one character of the string is matching with the regex object
- 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
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
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)
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();
}
}
JavaScript
function hasSpecialChar(str) {
let regex = /[@!#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/;
return regex.test(str);
}
let str = "Geeks$For$Geeks";
if (!hasSpecialChar(str)) {
console.log("String is accepted");
} else {
console.log("String is not accepted");
}
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
?>
OutputString 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
C#
using System;
class Program {
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[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) {
Console.WriteLine("string is not accepted");
}
else {
Console.WriteLine("string is accepted");
}
}
}
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");
}
Outputstring 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
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.");
}
}
}
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
C#
using System;
class GFG {
// This method checks if a string contains any special
// characters.
public static bool HasSpecialChar(string s)
{
// Iterate over each character in the string.
for (int i = 0; i < s.Length; i++) {
char c = s[i];
// If the character is not a letter, digit, or
// space, it is a special character.
if (!(char.IsLetterOrDigit(c) || c == ' ')) {
return true;
}
}
// If no special characters were found, return
// false.
return false;
}
static void Main(string[] args)
{
string s1 = "Hello World";
// Check if s1 contains any special characters and
// print the result.
if (HasSpecialChar(s1)) {
Console.WriteLine(
"The string contains special characters.");
}
else {
Console.WriteLine(
"The string does not contain special characters.");
}
string s2 = "Hello@World";
// Check if s2 contains any special characters and
// print the result.
if (HasSpecialChar(s2)) {
Console.WriteLine(
"The string contains special characters.");
}
else {
Console.WriteLine(
"The string does not contain special characters.");
}
}
}
JavaScript
function hasSpecialChar(s) {
for (let i = 0; i < s.length; i++) {
const c = s.charAt(i);
if (!(c.match(/^[a-zA-Z0-9 ]+$/))) {
return true;
}
}
return false;
}
let s = "Hello World";
if (hasSpecialChar(s)) {
console.log("The string contains special characters.");
} else {
console.log("The string does not contain special characters.");
}
s = "Hello@World";
if (hasSpecialChar(s)) {
console.log("The string contains special characters.");
} else {
console.log("The string does not contain special characters.");
}
OutputThe 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".
Python3
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
OutputString 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
public class Main {
// Function to check if a string contains only alphanumeric characters
static boolean checkSpecialCharASCII(String str) {
// Iterate through each character in the string
for (char c : str.toCharArray()) {
// Check if the character is not an alphanumeric character based on ASCII values
if (!(c >= '0' && c <= '9') && !(c >= 'A' && c <= 'Z') && !(c >= 'a' && c <= 'z')) {
return false; // If not alphanumeric, return false
}
}
return true; // If all characters are alphanumeric, return true
}
public static void main(String[] args) {
String str = "Geeks$For$Geeks";
// Check if the string contains only alphanumeric characters
if (checkSpecialCharASCII(str)) {
System.out.println("String is accepted."); // Print if accepted
} else {
System.out.println("String is not accepted."); // Print if not accepted
}
}
}
//This code is contributed by Adarsh.
Python3
def check_special_char_ascii(string):
for char in string:
if ord(char) < 48 or (57 < ord(char) < 65) or (90 < ord(char) < 97) or ord(char) > 122:
return "String is not accepted."
return "String is accepted."
# Example Usage
string = "Geeks$For$Geeks"
print(check_special_char_ascii(string))
C#
using System;
class Program
{
static string CheckSpecialCharASCII(string input)
{
// Loop through each character in the input string
foreach (char c in input)
{
// Check if the ASCII value of the character is less than 48 or greater than 122
if (c < 48 || (c > 57 && c < 65) || (c > 90 && c < 97) || c > 122)
{
return "String is not accepted.";
}
}
// If no special characters were found, return "String is accepted."
return "String is accepted.";
}
static void Main(string[] args)
{
string input = "Geeks$For$Geeks";
Console.WriteLine(CheckSpecialCharASCII(input));
}
}
JavaScript
// Function to check if a string contains only alphanumeric characters
function checkSpecialCharASCII(str) {
// Iterate through each character in the string
for (let i = 0; i < str.length; i++) {
const c = str.charAt(i);
// Check if the character is not an alphanumeric character based on ASCII values
if (!(c >= '0' && c <= '9') && !(c >= 'A' && c <= 'Z') && !(c >= 'a' && c <= 'z')) {
return false; // If not alphanumeric, return false
}
}
return true; // If all characters are alphanumeric, return true
}
// Main function
function main() {
const str = "Geeks$For$Geeks";
// Check if the string contains only alphanumeric characters
if (checkSpecialCharASCII(str)) {
console.log("String is accepted."); // Print if accepted
} else {
console.log("String is not accepted."); // Print if not accepted
}
}
// Call the main function
main();
OutputString 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).
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem