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 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++
#include <iostream>
#include <regex>
using namespace std;
void run(string str)
{
regex regx( "[@_!#$%^&*()<>?/|}{~:]" );
if (regex_search(str, regx) == 0)
cout << "String is accepted" ;
else
cout << "String is not accepted." ;
}
int main()
{
string str = "Geeks$For$Geeks" ;
run(str);
return 0;
}
|
Python3
import re
def run(string):
regex = re. compile ( '[@_!#$%^&*()<>?/\|}{~:]' )
if (regex.search(string) = = None ):
print ( "String is accepted" )
else :
print ( "String is not accepted." )
if __name__ = = '__main__' :
string = "Geeks$For$Geeks"
run(string)
|
PHP
<?Php
function run( $string )
{
$regex = preg_match( '[@_!#$%^&*()<>?/\|}{~:]' ,
$string );
if ( $regex )
print ( "String is accepted" );
else
print ( "String is not accepted." );
}
$string = 'Geeks$For$Geeks' ;
run( $string );
?>
|
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" );
}
}
}
|
C#
using System;
using System.Text.RegularExpressions;
class Program {
static void Run( string str)
{
Regex regex = new Regex( "[@_!#$%^&*()<>?/|}{~:]" );
if (!regex.IsMatch(str))
Console.WriteLine( "String is accepted" );
else
Console.WriteLine( "String is not accepted." );
}
static void Main()
{
string str = "Geeks$For$Geeks" ;
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");
}
|
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++
#include <iostream>
#include <string>
using namespace std;
int main()
{
string n = "Geeks$For$Geeks" ;
int c = 0;
string s
= "[@_!#$%^&*()<>?}{~:]" ;
for ( int i = 0; i < n.size(); i++) {
if (s.find(n[i]) != string::npos) {
c++;
}
}
if (c) {
cout << "string is not accepted" ;
}
else {
cout << "string is accepted" ;
}
return 0;
}
|
Java
import java.util.*;
class Main {
public static void main(String[] args)
{
String n = "Geeks$For$Geeks" ;
int c = 0 ;
String s = "[@_!#$%^&*()<>?}{~:]" ;
for ( int i = 0 ; i < n.length(); i++) {
if (s.indexOf(n.charAt(i)) != - 1 ) {
c++;
}
}
if (c > 0 ) {
System.out.println( "string is not accepted" );
}
else {
System.out.println( "string is accepted" );
}
}
}
|
Python3
n = "Geeks$For$Geeks"
n.split()
c = 0
s = '[@_!#$%^&*()<>?/\|}{~:]' # special character set
for i in range ( len (n)):
if n[i] in s:
c + = 1
if c:
print ( "string is not accepted" )
else :
print ( "string accepted" )
|
Javascript
const n = "Geeks$For$Geeks" ;
let c = 0;
const s = "[@_!#$%^&*()<>?}{~:]" ;
for (let i = 0; i < n.length; i++) {
if (s.includes(n[i])) {
c++;
}
}
if (c) {
console.log( "string is not accepted" );
} else {
console.log( "string is accepted" );
}
|
C#
using System;
class Program {
static void Main( string [] args)
{
string n = "Geeks$For$Geeks" ;
int c = 0;
string s = "[@_!#$%^&*()<>?}{~:]" ;
for ( int i = 0; i < n.Length; i++) {
if (s.IndexOf(n[i]) != -1) {
c++;
}
}
if (c > 0) {
Console.WriteLine( "string is not accepted" );
}
else {
Console.WriteLine( "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
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." )
|
C#
using System;
class GFG {
public static bool HasSpecialChar( string s)
{
for ( int i = 0; i < s.Length; i++) {
char c = s[i];
if (!( char .IsLetterOrDigit(c) || c == ' ' )) {
return true ;
}
}
return false ;
}
static void Main( string [] args)
{
string s1 = "Hello World" ;
if (HasSpecialChar(s1)) {
Console.WriteLine(
"The string contains special characters." );
}
else {
Console.WriteLine(
"The string does not contain special characters." );
}
string s2 = "Hello@World" ;
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" )
check_string( "Geeks$For$Geeks" )
check_string( "Geeks For Geeks" )
|
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”.
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."
string = "Geeks$For$Geeks"
print (check_special_char_ascii(string))
|
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).