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++
// 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 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
Java
// 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);
}
}
Python3
# 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
C#
// 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
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>
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++
// C++ program to check if the string
// contains only special characters
#include <bits/stdc++.h>
using namespace std;
// Function to check if the string contains only special characters.
void Check_Special_Chars(string s)
{
// Looping over the string
for(int i = 0; i<s.length();i++)
{
// checking for a-z and A-Z characters
for(int k = 0; k <26; k++)
{
// if present then print No and return
if(s[i]==k+65 || s[i]==k+97)
{
cout<<"No"<<endl;
return;
}
}
// Checking for 0-9 characters
for(int k = 0; k<10; k++)
{
// if present then print No and return
if(s[i]==k+48)
{
cout<<"No"<<endl;
return;
}
}
}
// if not present a-z, A-Z and 0-9, then only special character present and print Yes
cout<<"Yes"<<endl;
}
// Driver Code
int main()
{
// Given string str
string str = "@#$&%!~";
Check_Special_Chars(str) ;
return 0;
}
Java
import java.util.*;
class Main {
// Function to check if the string contains only special characters.
static void Check_Special_Chars(String s) {
// Looping over the string
for(int i = 0; i < s.length(); i++) {
// checking for a-z and A-Z characters
for(int k = 0; k < 26; k++) {
// if present then print No and return
if(s.charAt(i) == (char)(k + 65) || s.charAt(i) == (char)(k + 97)) {
System.out.println("No");
return;
}
}
// Checking for 0-9 characters
for(int k = 0; k < 10; k++) {
// if present then print No and return
if(s.charAt(i) == (char)(k + 48)) {
System.out.println("No");
return;
}
}
}
// if not present a-z, A-Z and 0-9, then only special character present and print Yes
System.out.println("Yes");
}
// Driver Code
public static void main(String[] args) {
// Given string str
String str = "@#$&%!~";
Check_Special_Chars(str);
}
}
Python3
class Main:
# Function to check if the string contains only special characters.
@staticmethod
def Check_Special_Chars(s):
# Looping over the string
for i in range(len(s)):
# checking for a-z and A-Z characters
for k in range(26):
# if present then print No and return
if s[i] == chr(k + 65) or s[i] == chr(k + 97):
print("No")
return
# Checking for 0-9 characters
for k in range(10):
# if present then print No and return
if s[i] == chr(k + 48):
print("No")
return
# if not present a-z, A-Z and 0-9, then only special character
# present and print Yes
print("Yes")
# Driver Code
# Given string str
str = "@#$&%!~"
Main.Check_Special_Chars(str)
C#
using System;
class Program
{
// Function to check if the string contains only special
// characters.
static void Check_Special_Chars(string s)
{
// Looping over the string
for (int i = 0; i < s.Length; i++)
{
// checking for a-z and A-Z characters
for (int k = 0; k < 26; k++)
{
// if present then print No and return
if (s[i] == k + 65 || s[i] == k + 97) {
Console.WriteLine("No");
return;
}
}
// Checking for 0-9 characters
for (int k = 0; k < 10; k++)
{
// if present then print No and return
if (s[i] == k + 48) {
Console.WriteLine("No");
return;
}
}
}
// if not present a-z, A-Z and 0-9, then only
// special character present and print Yes
Console.WriteLine("Yes");
}
// Driver Code
static void Main(string[] args)
{
// Given string str
string str = "@#$&%!~";
Check_Special_Chars(str);
}
}
JavaScript
// Function to check if the string contains only special characters.
function Check_Special_Chars(s) {
// Looping over the string
for (let i = 0; i < s.length; i++) {
// checking for a-z and A-Z characters
for (let k = 0; k < 26; k++) {
// if present then print No and return
if (s[i] == String.fromCharCode(k + 65) || s[i] == String.fromCharCode(k + 97)) {
console.log("No");
return;
}
}
// Checking for 0-9 characters
for (let k = 0; k < 10; k++) {
// if present then print No and return
if (s[i] == String.fromCharCode(k + 48)) {
console.log("No");
return;
}
}
}
// if not present a-z, A-Z and 0-9, then only special character present and print Yes
console.log("Yes");
}
// Driver Code
let str = "@#$&%!~";
Check_Special_Chars(str);
Time Complexity: O(N)
Auxiliary Space: O(1)
Similar Reads
Check if a String Contains only Alphabets in Java
In Java, to check if a string contains only alphabets, we have to verify each character to make sure it falls within the range of valid alphabetic characters. There are various ways to check this in Java, depending on requirements.Example: The most common and straightforward approach to validate if
4 min read
Python program to check if a string contains all unique characters
To implement an algorithm to determine if a string contains all unique characters. Examples: Input : s = "abcd" Output: True "abcd" doesn't contain any duplicates. Hence the output is True. Input : s = "abbd" Output: False "abbd" contains duplicates. Hence the output is False. One solution is to cre
3 min read
Check if both halves of the string have same set of characters
Given a string of lowercase characters only, the task is to check if it is possible to split a string from the middle which will give two halves having the same characters and same frequency of each character. If the length of the given string is ODD then ignore the middle element and check for the
12 min read
Check if a String Contains only Alphabets in Java using Regex
Regular Expressions or Regex is an API for defining String patterns that can be used for searching, manipulating, and editing a text. It is widely used to define a constraint on strings such as a password. Regular Expressions are provided under java.util.regex package. For any string, here the task
2 min read
Program to count vowels, consonant, digits and special characters in string.
Given a string and the task is to count vowels, consonant, digits and special character in string. Special character also contains the white space.Examples: Input : str = "geeks for geeks121" Output : Vowels: 5 Consonant: 8 Digit: 3 Special Character: 2 Input : str = " A1 B@ d adc" Output : Vowels:
6 min read
Check if uppercase characters in a string are used correctly or not
Given a string S consisting of uppercase and lowercase letters, the task is to check if uppercase characters are used correctly in the given string or not. Correct usage of uppercase characters are as follows: All characters in the string are in uppercase. For example, "GEEKS".None of the characters
8 min read
Program to check if first and the last characters of string are equal
We are given a string, we need to check whether the first and last characters of the string str are equal or not. Case sensitivity is to be considered. Examples : Input : university Output : Not Equal Explanation: In the string "university", the first character is 'u' and the last character is 'y',
4 min read
Check if both halves of the string have same set of characters in Python
Given a string of lowercase characters only, the task is to check if it is possible to split a string from middle which will gives two halves having the same characters and same frequency of each character. If the length of the given string is ODD then ignore the middle element and check for the res
3 min read
Quick way to check if all the characters of a string are same
Given a string, check if all the characters of the string are the same or not. Examples: Input : s = "geeks"Output : No Input : s = "gggg" Output : Yes Recommended PracticeCheck StringTry It! Simple Way To find whether a string has all the same characters. Traverse the whole string from index 1 and
8 min read
Check if the characters in a string form a Palindrome in O(1) extra space
Given string str. The string may contain lower-case letters, special characters, digits, or even white spaces. The task is to check whether only the letters present in the string are forming a Palindromic combination or not without using any extra space. Note: It is not allowed to use extra space to
10 min read