Java Program to Check Whether the String Consists of Special Characters
Last Updated :
28 Nov, 2024
In Java, special characters refer to symbols other than letters and digits, such as @
, #
, !
, etc. To check whether the String consists of special characters, there are multiple ways, including using the Character
class, regular expressions, or simple string checks.
Example:
In this example, we will use the Character.isLetterOrDigit()
method that checks if a string consists of special characters. If the character is not a letter or digit, it is considered a special character. This is a simple and efficient method to identify special characters.
Java
// Java Program to Check if String
// contains Special Characters
// using Character.isLetterOrDigit()
import java.io.*;
class GFG {
public static void main(String[] args) {
String s = "!#$GeeeksforGeeks.Computer.Science.Portal!!";
// Count for special characters
int count = 0;
// Iterating through the string to
// check for special characters
for (int i = 0; i < s.length(); i++) {
// If character is not a letter, digit, or space,
// it's a special character
if (!Character.isLetterOrDigit(s.charAt(i))
&& !Character.isWhitespace(s.charAt(i))) {
count++; // Increment count for special characters
}
}
// Displaying the result
if (count > 0) {
System.out.println("Special characters found: " + count);
} else {
System.out.println("No Special Characters found.");
}
}
}
OutputSpecial characters found: 8
Explanation: In the above example, the program iterates through each character of the given string. It uses Character.isLetterOrDigit()
to check if the character is a letter or a digit. If not, it counts as a special character.
Other Methods to Check if a String Consists of Special Characters
1. Using Regular Expressions
We can use Regular expressions to check special characters. The regex [^a-zA-Z0-9 ]
matches any character that is not a letter, digit, or space. Below are the steps to implement:
- Create a regular expression that does not match any letters, digits, or whitespace.
- We will use Matcher class in accordance with regular expression with our input string.
- Now, if there exist any "character matches" with the regular expression, then the string contains special characters, otherwise it does not contain any special characters.
- Print the result.
Java
// Java Program to Check Whether String contains Special
// Characters using Regex classes
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GFG {
public static void main(String[] args) {
String s1 = "GeeksForGeeks";
// Creating regex pattern by
// creating object of Pattern class
Pattern p = Pattern.compile(
"[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
// Creating matcher for above
// pattern on our string
Matcher m = p.matcher(s1);
// Now finding the matches for which
// let us set a boolean flag and
// imposing find() method
boolean res = m.find();
// If special characters are found
if (res)
// Display this message on the console
System.out.println(
"String1 contains Special Characters.");
// If we reach here means
// no special characters are found
else
// Display this message on the console
System.out.println(
"No Special Characters found in String 1.");
String s2 = "!!Geeks.For.Geeks##";
Matcher m2 = p.matcher(s2);
boolean res2 = m2.find();
if (res2)
System.out.println(
"String 2 contains Special Characters.");
else
System.out.println(
"No Special Characters found in String 2.");
}
}
OutputNo Special Characters found in String 1.
String 2 contains Special Characters.
2. Using String.contains() Method
The contains()
method of String class checks if a specific substring exists within the string. Here, we can use it to check if any character in the input string is not part of a predefined set of allowed characters (letters, digits, and spaces).
Java
// Java Program to Check Whether String
// contains Special Characters using String.contains()
import java.util.*;
public class GFG {
public static void main(String[] args) {
String s1 = "!#$GeeeksforGeeks.Computer.Science.Portal!!";
// Define a string of allowed characters
// (letters, digits, and spaces)
String s2 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ";
// Loop through each character in the input string
for (int i = 0; i < s1.length(); i++) {
// Check if the character is not
// in the allowed characters set
if (!s2.contains(String.valueOf(s1.charAt(i)))) {
System.out.println("String contains special characters.");
return;
}
}
System.out.println("No special characters found.");
}
}
OutputString contains special characters.
Explanation: In the above example, we define a string of allowed characters, including letters, digits, and spaces. It checks each character in the input string using contains()
method
.
Similar Reads
Java Program to Check Whether the Character is Vowel or Consonant In this article, we are going to learn how to check whether a character is a vowel or a consonant. So, the task is, for any given character, we need to check if it is a vowel or a consonant. As we know, vowels are âaâ, âeâ, âiâ, âoâ, âuâ and all the other characters (i.e. âbâ, âcâ, âdâ, âfâ â¦..) are
4 min read
Check if a string contains uppercase, lowercase, special characters and numeric values Given string str of length N, the task is to check whether the given string contains uppercase alphabets, lowercase alphabets, special characters, and numeric values or not. If the string contains all of them, then print "Yes". Otherwise, print "No". Examples: Input: str = "#GeeksForGeeks123@" Outpu
5 min read
How to Convert a String to Specific Character Encoding in Java? In Java, the process of converting a String to a certain character encoding is converting the string's character sequence to a byte array and applying the chosen character encoding. Java Program to Convert a String to a Specific Character EncodingUsing the String class's getBytes() function to trans
2 min read
How to Check if One String is a Rotation of Another in Java? In Java, to check if one string is a rotation of another, we can do string concatenation and substring matching. A rotated string is created by moving some characters from the beginning of the string to the end while maintaining the character order.Program to Check if One String is a Rotation of Ano
2 min read
How to Check if a String contains only ASCII in Java? The full form of ASCII is the American Standard Code for Information Interchange. It is the numeric representation of Character. As Java supports multiple languages, and it follows the Unicode system. In simple terms for better understanding, it converts the Character to a specific unique number, an
3 min read
How to Check if a String Contains Only Lowercase Letters in Java? A string is a data structure that contains a set of characters. It can be a word or can be a sentence. Also, it can be empty or can have a single letter. A string can contain Uppercase letters, Lowercase letters, or numbers of special characters. In this article, we will learn how to check if a Stri
4 min read
How to Check if a String Contains only Digits in Java? In Java, to check if a string contains only digits, we can use various methods such as simple iteration, regular expressions, streams, etc.Example:The example below uses the Character.isDigit() method to check each character of the string to ensure all characters are digits. This is the most simple
3 min read
Check if a given string is Pangram in Java Given string str, the task is to write Java Program check whether the given string is a pangram or not. A string is a pangram string if it contains all the character of the alphabets ignoring the case of the alphabets. Examples: Input: str = "Abcdefghijklmnopqrstuvwxyz"Output: YesExplanation: The gi
3 min read
How to remove all non-alphanumeric characters from a string in Java Given string str, the task is to remove all non-alphanumeric characters from it and print the modified it. Examples: Input: @!Geeks-for'Geeks,123 Output: GeeksforGeeks123 Explanation: at symbol(@), exclamation point(!), dash(-), apostrophes('), and commas(, ) are removed.Input: Geeks_for$ Geeks?{}[]
3 min read
Remove uppercase, lowercase, special, numeric, and non-numeric characters from a String Given string str of length N, the task is to remove uppercase, lowercase, special, numeric, and non-numeric characters from this string and print the string after the simultaneous modifications. Examples: Input: str = âGFGgfg123$%â Output: After removing uppercase characters: gfg123$% After removing
10 min read