Check if a string consists only of special characters - GeeksforGeeks

11 May, 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: YesExplanation: Given string contains only special characters. Therefore, the output is Yes.
Input: str = “Geeks4Geeks@#”Output: NoExplanation: 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++
Java
Python3
C#
Javascript
// 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 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);    }}
# 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# 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
<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)
princi singh
avanitrachhadiya2155
yuvraj_chandra
rdtank
ASCII
Java-String-Programs
regular-expression
strings
Pattern Searching
Strings
Strings
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Minimize number of cuts required to break N length stick into N unit length sticks
Check if an URL is valid or not using Regular Expression
How to check if string contains only digits in Java
String matching where one string contains wildcard characters
Pattern Searching using Suffix Tree
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
C++ Data Types