Check if a string consists only of special characters
Last Updated :
12 Apr, 2023
Given string str of length N, the task is to check if the given string contains only special characters or not. If the string contains only special characters, then print “Yes”. Otherwise, print “No”.
Examples:
Input: str = “@#$&%!~”
Output: Yes
Explanation:
Given string contains only special characters.
Therefore, the output is Yes.
Input: str = “Geeks4Geeks@#”
Output: No
Explanation:
Given string contains alphabets, number, and special characters.
Therefore, the output is No.
Naive Approach: Iterate over the string and check if the string contains only special characters or not. Follow the steps below to solve the problem:
- Traverse the string and for each character, check if its ASCII value lies in the ranges [32, 47], [58, 64], [91, 96] or [123, 126]. If found to be true, it is a special character.
- Print Yes if all characters lie in one of the aforementioned ranges. Otherwise, print No.
Time Complexity: O(N)
Auxiliary Space: O(1)
Space-Efficient Approach: The idea is to use Regular Expression to optimize the above approach. Follow the steps below:
- Create the following regular expression to check if the given string contains only special characters or not.
regex = “[^a-zA-Z0-9]+”
where,
- [^a-zA-Z0-9] represents only special characters.
- + represents one or more times.
- Match the given string with the Regular Expression using Pattern.matcher() in Java
- Print Yes if the string matches with the given regular expression. Otherwise, print No.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <regex>
using namespace std;
void onlySpecialCharacters(string str)
{
const regex pattern( "[^a-zA-Z0-9]+" );
if (str.empty())
{
cout<< "No" ;
return ;
}
if (regex_match(str, pattern))
{
cout<< "Yes" ;
}
else
{
cout<< "No" ;
}
}
int main()
{
string str = "@#$&%!~" ;
onlySpecialCharacters(str) ;
return 0;
}
|
Java
import java.util.regex.*;
class GFG {
public static void onlySpecialCharacters(
String str)
{
String regex = "[^a-zA-Z0-9]+" ;
Pattern p = Pattern.compile(regex);
if (str == null ) {
System.out.println( "No" );
return ;
}
Matcher m = p.matcher(str);
if (m.matches())
System.out.println( "Yes" );
else
System.out.println( "No" );
}
public static void main(String args[])
{
String str = "@#$&%!~" ;
onlySpecialCharacters(str);
}
}
|
Python3
import re
def onlySpecialCharacters( Str ):
regex = "[^a-zA-Z0-9]+"
p = re. compile (regex)
if ( len ( Str ) = = 0 ):
print ( "No" )
return
if (re.search(p, Str )):
print ( "Yes" )
else :
print ( "No" )
Str = "@#$&%!~"
onlySpecialCharacters( Str )
|
C#
using System;
using System.Text.RegularExpressions;
class GFG{
public static void onlySpecialchars(String str)
{
String regex = "[^a-zA-Z0-9]+" ;
Regex rgex = new Regex(regex);
if (str == null )
{
Console.WriteLine( "No" );
return ;
}
MatchCollection matchedAuthors =
rgex.Matches(str);
if (matchedAuthors.Count != 0)
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
public static void Main(String []args)
{
String str = "@#$&%!~" ;
onlySpecialchars(str);
}
}
|
Javascript
<script>
function onlySpecialchars(str)
{
var regex = /^[^a-zA-Z0-9]+$/;
if (str.length < 1) {
document.write( "No" );
return ;
}
var matchedAuthors = regex.test(str);
if (matchedAuthors) document.write( "Yes" );
else document.write( "No" );
}
var str = "@#$&%!~" ;
onlySpecialchars(str);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Another approach: This is simple approach in which just checking the string contain any alphabets and digits or not. If contains then print No else print Yes.
1. Take the a string str and call the function Check_Special_Chars passing string as parameter.
2. The function Check_Special_Chars takes a string as input and loops over each character in the string using a for loop.
3. Now in the inner loop check each character is an alphabet (both upper and lower case) A to Z ASCII value (65 to 90) and a to z ASCII value(97 to 122) or not.
If the character is an alphabet, the function prints “No” and returns from the function.
4.The second inner for loop checks if the current character is a number (0 to 9) ASCII value(48 to 57). If the character is a number, the function prints “No” and returns from the function.
5. If the function loops through the entire string without finding any alphabets or numbers, it means that the string only contains special characters. In this case, the function prints “Yes”.
Below the implementation of above approach.
C++
#include <bits/stdc++.h>
using namespace std;
void Check_Special_Chars(string s)
{
for ( int i = 0; i<s.length();i++)
{
for ( int k = 0; k <26; k++)
{
if (s[i]==k+65 || s[i]==k+97)
{
cout<< "No" <<endl;
return ;
}
}
for ( int k = 0; k<10; k++)
{
if (s[i]==k+48)
{
cout<< "No" <<endl;
return ;
}
}
}
cout<< "Yes" <<endl;
}
int main()
{
string str = "@#$&%!~" ;
Check_Special_Chars(str) ;
return 0;
}
|
Java
import java.util.*;
class Main {
static void Check_Special_Chars(String s) {
for ( int i = 0 ; i < s.length(); i++) {
for ( int k = 0 ; k < 26 ; k++) {
if (s.charAt(i) == ( char )(k + 65 ) || s.charAt(i) == ( char )(k + 97 )) {
System.out.println( "No" );
return ;
}
}
for ( int k = 0 ; k < 10 ; k++) {
if (s.charAt(i) == ( char )(k + 48 )) {
System.out.println( "No" );
return ;
}
}
}
System.out.println( "Yes" );
}
public static void main(String[] args) {
String str = "@#$&%!~" ;
Check_Special_Chars(str);
}
}
|
Python3
class Main:
@staticmethod
def Check_Special_Chars(s):
for i in range ( len (s)):
for k in range ( 26 ):
if s[i] = = chr (k + 65 ) or s[i] = = chr (k + 97 ):
print ( "No" )
return
for k in range ( 10 ):
if s[i] = = chr (k + 48 ):
print ( "No" )
return
print ( "Yes" )
str = "@#$&%!~"
Main.Check_Special_Chars( str )
|
C#
using System;
class Program
{
static void Check_Special_Chars( string s)
{
for ( int i = 0; i < s.Length; i++)
{
for ( int k = 0; k < 26; k++)
{
if (s[i] == k + 65 || s[i] == k + 97) {
Console.WriteLine( "No" );
return ;
}
}
for ( int k = 0; k < 10; k++)
{
if (s[i] == k + 48) {
Console.WriteLine( "No" );
return ;
}
}
}
Console.WriteLine( "Yes" );
}
static void Main( string [] args)
{
string str = "@#$&%!~" ;
Check_Special_Chars(str);
}
}
|
Javascript
function Check_Special_Chars(s) {
for (let i = 0; i < s.length; i++) {
for (let k = 0; k < 26; k++) {
if (s[i] == String.fromCharCode(k + 65) || s[i] == String.fromCharCode(k + 97)) {
console.log( "No" );
return ;
}
}
for (let k = 0; k < 10; k++) {
if (s[i] == String.fromCharCode(k + 48)) {
console.log( "No" );
return ;
}
}
}
console.log( "Yes" );
}
let str = "@#$&%!~" ;
Check_Special_Chars(str);
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...