Skip to content
Related Articles

Related Articles

Check if a string consists only of special characters
  • Last Updated : 03 Feb, 2021

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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to check if the string
// contains only special characters
#include <iostream>
#include <regex>
using namespace std;
 
// Function to check if the string contains only special characters.
void onlySpecialCharacters(string str)
{
 
  // Regex to check if the string contains only special characters.
  const regex pattern("[^a-zA-Z0-9]+");
 
 
  // If the string
  // is empty then print "No"
  if (str.empty())
  {
     cout<< "No";
     return ;
  }
 
  // Print "Yes" if the the string contains only special characters
  // matched the ReGex
  if(regex_match(str, pattern))
  {
    cout<< "Yes";
  }
  else
  {
    cout<< "No";
  }
}
 
// Driver Code
int main()
{
   
  // Given string str
  string str = "@#$&%!~";
  onlySpecialCharacters(str) ;
 
  return 0;
}
 
// This code is contributed by yuvraj_chandra

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to check if the string
// contains only special characters
 
import java.util.regex.*;
class GFG {
 
    // Function to check if a string
    // contains only special characters
    public static void onlySpecialCharacters(
        String str)
    {
 
        // Regex to check if a string contains
        // only special characters
        String regex = "[^a-zA-Z0-9]+";
 
        // Compile the ReGex
        Pattern p = Pattern.compile(regex);
 
        // If the string is empty
        // then print No
        if (str == null) {
            System.out.println("No");
            return;
        }
 
        // Find match between given string
        // & regular expression
        Matcher m = p.matcher(str);
 
        // Print Yes If the string matches
        // with the Regex
        if (m.matches())
            System.out.println("Yes");
        else
            System.out.println("No");
    }
 
    // Driver Code
    public static void main(String args[])
    {
        // Given string str
        String str = "@#$&%!~";
 
        // Function Call
        onlySpecialCharacters(str);
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to check if the string
# contains only special characters
import re
 
# Function to check if a string
# contains only special characters
def onlySpecialCharacters(Str):
 
    # Regex to check if a string contains
    # only special characters
    regex = "[^a-zA-Z0-9]+"
 
    # Compile the ReGex
    p=re.compile(regex)
 
    # If the string is empty
    # then print No
    if(len(Str) == 0):
        print("No")
        return
 
    # Print Yes If the string matches
    # with the Regex
    if(re.search(p, Str)):
        print("Yes")
    else:
        print("No")
 
# Driver Code
 
# Given string str
Str = "@#$&%!~"
 
# Function Call
onlySpecialCharacters(Str)
 
# This code is contributed by avanitrachhadiya2155

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to check if
// the string contains only
// special characters
using System;
using System.Text.RegularExpressions; 
class GFG{
 
// Function to check if a string
// contains only special characters
public static void onlySpecialchars(String str)
{
  // Regex to check if a string
  // contains only special
  // characters
  String regex = "[^a-zA-Z0-9]+";
 
  // Compile the ReGex
  Regex rgex = new Regex(regex); 
 
  // If the string is empty
  // then print No
  if (str == null)
  {
    Console.WriteLine("No");
    return;
  }
 
  // Find match between given
  // string & regular expression
  MatchCollection matchedAuthors =
                  rgex.Matches(str);   
 
  // Print Yes If the string matches
  // with the Regex
  if (matchedAuthors.Count != 0)
    Console.WriteLine("Yes");
  else
    Console.WriteLine("No");
}
 
// Driver Code
public static void Main(String []args)
{
  // Given string str
  String str = "@#$&%!~";
 
  // Function Call
  onlySpecialchars(str);
}
}
 
// This code is contributed by Princi Singh

chevron_right


Output: 

Yes

 

Time Complexity: O(N)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :