Special characters are those characters that are neither a letter nor a number. Whitespace is also not considered a special character. Examples of special characters are:- !(exclamation mark), , (comma), #(hash), etc.
Method 1: Using Character class
The approach is as follows:
- Iterate through all the characters of the string.
- Alongside we will be checking each character for being a letter, a digit, or whitespace using the java character class.
- It is found to be none of the above signifying special characters.
- Parallelly we will maintain a counter for special character count.
- Lastly, print and display the required count or special characters as per the need.
String has Special Characters 8 Special Characters found.
Method 2: Using regular expressions
- 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.
No Special Characters found in String 1 String 2 contains Special Characters
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections 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.