Check if a string consists only of special characters
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:
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.
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++
// 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 Codeint main(){ // Given string str string str = "@#$&%!~"; onlySpecialCharacters(str) ; return 0;}// This code is contributed by yuvraj_chandra |
Java
// Java program to check if the string// contains only special charactersimport 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); }} |
Python3
# Python program to check if the string# contains only special charactersimport re# Function to check if a string# contains only special charactersdef 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 strStr = "@#$&%!~"# Function CallonlySpecialCharacters(Str)# This code is contributed by avanitrachhadiya2155 |
C#
// C# program to check if// the string contains only// special charactersusing System;using System.Text.RegularExpressions; class GFG{// Function to check if a string// contains only special characterspublic 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 Codepublic static void Main(String []args){ // Given string str String str = "@#$&%!~"; // Function Call onlySpecialchars(str);}}// This code is contributed by Princi Singh |
Javascript
<script> // JavaScript program to check if // the string contains only // special characters // Function to check if a string // contains only special characters function onlySpecialchars(str) { // Regex to check if a string // contains only special // characters var regex = /^[^a-zA-Z0-9]+$/; // If the string is empty // then print No if (str.length < 1) { document.write("No"); return; } // Find match between given // string & regular expression var matchedAuthors = regex.test(str); // Print Yes If the string matches // with the Regex if (matchedAuthors) document.write("Yes"); else document.write("No"); } // Driver Code // Given string str var str = "@#$&%!~"; // Function Call onlySpecialchars(str); </script> |
Yes
Time Complexity: O(N)
Auxiliary Space: O(1)


