How To Check String Contains Special Characters In Java?

Strings are an integral part of programming in Java. Whether you are dealing with user input, file processing, or data manipulation, understanding how to work with strings is essential.

One common task when handling strings is checking for the presence of special characters. Special characters can have various meanings and uses, but sometimes you just want to identify their existence within a string.

In this post, we will discuss how to check string contains special characters in java. We have used 3 ways regex, ASCII value, and Special Characters.

What is a Special Character?

According to Computerhope, a Special character is a character other than an alphabetic or numeric character. Examples of special characters are Punctuation marks and other symbols.

How to check string contains special characters in Java?

We can check whether the given string contains any special characters or not by using the below approaches:

  1. Check special characters in java using ASCII value.
  2. Check special characters in java using regex.
  3. Check special characters in Java using all special characters.
UsageValue
ASCIIRange [32, 47], [58, 64], [91, 96] & [123, 126] of ASCII Table.
Regex[^a-zA-Z0-9]
Special Characters!@#$%&*()’+,-./:;<=>?[]^_`{|}

Note: You can also refer to ASCII Table to get complete knowledge about ASCII values.

Read Also: How To Reverse A String In Java – Learn 5 Easy Methods

Let’s see all approaches with programs to check special characters in Strings.

Approach-1: How to check String contains special characters in java using ASCII value?

In this approach, We will use ASCII values to check whether characters of a String contain any special character or not.

As we have already given all ranges of ASCII values of special characters in the above table, we have to check for each range of ASCII values in the Java program.

Let’s see the program here.

Java program using ASCII value:

/**
 * How to check special characters in java using ASCII value
 */
package cf.java.string;

import java.util.Scanner;

public class CheckSpecialCharacters {

	public static void main(String[] args) {
		// Declare variables
		String str;
		Scanner sc = new Scanner(System.in);
		// Accept any String
		System.out.print("Enter any String to check: ");
		str = sc.nextLine();
		boolean check = false;
		// Use for loop to check special characters
		for (int i = 0; i < str.length(); i++) {
			int asciiVal = (int) str.charAt(i);
			// Check whether String contains special character or not
			if ((asciiVal >= 32 && asciiVal <= 47) || (asciiVal >= 58 && asciiVal <= 64)
					|| (asciiVal >= 91 && asciiVal <= 96) || (asciiVal >= 123 && asciiVal <= 126)) {
				check = true;
				break;
			}
		}
		if (check)
			System.out.println("Given String contains special character!");
		else
			System.out.println("Given String doesn't contain any special characters");
	}

}
Code language: Java (java)

Output:

Enter any String to check: Codingface@1234
Given String contains special character!Code language: JavaScript (javascript)

Explanation of ASCII value program:

In the above program first, we will accept any String from the user(Lines no 15 & 16). Then we used for loop for(int i = 0; i < str.length(); i++) to iterate a given String.

We have declared the asciiVal variable to store the ASCII value of each character before checking for a special character and we will use this asciiVal to check in if( ) condition.

In the if( ) condition, we have taken multiple conditions to check for ASCII values. If the String contains any special characters, then we will change the value of the check to true. otherwise check will remain false. We have declared a boolean variable check (boolean check = false;) to use for true or false. So that by using this check variable we can display whether the given String contains any special character or not.

Finally, we have displayed the result using the print( ) method.

Read Also: How To Find Power Of A Number In Java – 3 Simple Ways

Approach-2: How to check String contains special characters in java using regex?

In this approach, we will use regex with java.util.regex.Matcher and java.util.regex.Pattern classes to check special characters in a String.

Let’s see the program here.

Java program using regex:

/**
 * How to check String contains special characters in Java using regex?
 */
package cf.java.string;

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CheckSpecialCharactersUsingRegex {

	public static void main(String[] args) {
		// Declare variables
		String str;
		Pattern checkPattern;
		Matcher match;
		boolean check;

		Scanner sc = new Scanner(System.in);
		// Accept any String
		System.out.print("Enter any String to check: ");
		str = sc.nextLine();

		// Declare pattern of special characters
		checkPattern = Pattern.compile("[^a-zA-Z0-9]");
		// Declare matcher to match with String
		match = checkPattern.matcher(str);
		// Use find( ) function to check
		check = match.find();
		// Check whether String contains any special characters or not and display
		// accordingly
		if (check)
			System.out.println("Given String contains special character!");
		else
			System.out.println("Given String doesn't contain any special characters");
	}

}
Code language: Java (java)

Output:

Enter any String to check: Codingface@1234
Given String contains special character!Code language: JavaScript (javascript)

Explanation of regex program:

In the above program, we have used the regex pattern [^a-zA-Z0-9] to check for all special characters.

First, we have compiled the given regex using the compile( ) method of java.util.regex.Pattern class and then we matched this pattern with the given String using the matcher( ) method of java.util.regex.Matcher class.

Finally, we have checked whether the given pattern of regex was found in String or not by using the find( ) function which returns the type is a boolean. So find( ) the function will return either true or false and by using this check, we have displayed the result to the user.

Read Also: Java Program To Print Vowels In A String – 2 Simple Programs

Approach-3: How to check String contains special characters in java using all special characters?

In this approach, we will all special characters directly to check whether those special characters are present in a String or not.

Let’s check the program now.

Java program using special characters:

package cf.java.string;

import java.util.Scanner;

public class CheckSpecialCharactersUsingAllSpclChars {

	public static void main(String[] args) {
		// Declare variables
		String str;
		Scanner sc = new Scanner(System.in);
		// Accept any String
		System.out.print("Enter any String to check: ");
		str = sc.nextLine();
		String specialChars = "!@#$%&*()'+,-./:;<=>?[]^_`{|}";
		boolean check = false;
		// Use for loop to check special characters
		for (int i = 0; i < str.length(); i++) {
			String strChar = Character.toString(str.charAt(i));
			// Check whether String contains special character or not
			if (specialChars.contains(strChar)) {
				check = true;
				break;
			}
		}
		if (check)
			System.out.println("Given String contains special character!");
		else
			System.out.println("Given String doesn't contain any special characters");

	}

}
Code language: JavaScript (javascript)

Output:

Enter any String to check: Codingface@1234
Given String contains special character!Code language: JavaScript (javascript)

Explanation of special characters program:

In the above program first, we have declared all special characters in a String as String specialChars = “!@#$%&*()’+,-./:;<=>?[]^_`{|}”;specialChars.

Then by using the for loop, we have iterated the given String from index 0 to the last index. Inside for loop, we have declared a String strChar to store each character as String and then we have checked whether this String is present in specialChars String or not. If it is available then we will change the value of the check to true otherwise, it remains false.

Finally,  by using the check variable we have displayed the result to the user.

Read Also: How To Find Multiples Of A Float Value In Java?

Conclusion

In this tutorial, we explored three distinct methods to identify special characters within a given string. Special characters, such as symbols and punctuation marks, are essential considerations in text processing.

  • Using ASCII values: This approach employs character ASCII values to meticulously inspect each character within the string for special character ranges. While precise, it can be more verbose.
  • Regular Expressions (Regex): Leveraging regex simplifies the process. We create a pattern that matches any character not belonging to the alphanumeric set. This method streamlines the code for concise execution.
  • Direct comparison: By comparing each character in the input string to a predefined set of special characters, this method provides a straightforward solution. If a match is found, the string contains a special character.

These methods provide flexibility in checking for special characters in a string, and you can choose the one that best fits your specific requirements.

Other readers also ask for:

  • How to check string contains special characters in java?
  • How to find special characters in a string in java?
  • How to check special characters in a string in java?
  • How to check if a string contains special characters in java?
  • How to check if the string contains special characters in java?

FAQs

What is a Special Character?

A special character is a character other than an alphabetic or numeric character. Examples of special characters are Punctuation marks and other symbols.

How to check string contains special characters in Java?

We can check whether the given string contains any special characters or not by using the below approaches:
Check special characters in java using ASCII value.
Check special characters in java using regex.
Check special characters in Java using all special characters.

What are the Special Characters?

Special Characters include !@#$%&*()’+,-./:;<=>?[]^_`{|}.

Which regex we can use to find Special Characters?

Regex: [^a-zA-Z0-9]

3 thoughts on “How To Check String Contains Special Characters In Java?”

Leave a Comment