Check if a string consists only of special characters - GeeksforGeeks (2024)

Improve

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>

 
 

Output:

Yes

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);

 
 

Output

Yes

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



Last Updated : 12 Apr, 2023

Like Article

Save Article

Previous

How to validate Indian Passport number using Regular Expression

Next

Find all matrix elements which are minimum in their row and maximum in their column

Share your thoughts in the comments

Please Login to comment...

Check if a string consists only of special characters - GeeksforGeeks (2024)
Top Articles
Latest Posts
Article information

Author: Allyn Kozey

Last Updated:

Views: 5856

Rating: 4.2 / 5 (43 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Allyn Kozey

Birthday: 1993-12-21

Address: Suite 454 40343 Larson Union, Port Melia, TX 16164

Phone: +2456904400762

Job: Investor Administrator

Hobby: Sketching, Puzzles, Pet, Mountaineering, Skydiving, Dowsing, Sports

Introduction: My name is Allyn Kozey, I am a outstanding, colorful, adventurous, encouraging, zealous, tender, helpful person who loves writing and wants to share my knowledge and understanding with you.