Java program to find and print all special characters with their positions in a string
Program to Find Special Characters in a String
In this section, you will learn how to find special characters from a string in Java along with counting the total number of special characters with their positions in a given string.
Overview
This Java program demonstrates how to use regular expressions to find and count special characters in a string. Special characters are any characters that are not letters (a-z, A-Z), numbers (0-9), or spaces.
Complete Program
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Scanner;
class FindSpecialCharacters {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String str;
System.out.print("\nEnter a string : ");
str = input.nextLine();
Pattern string_patterns = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Matcher string_matcher = string_patterns.matcher(str);
System.out.println("\n\n\t______________ OUTPUT ______________");
System.out.println("\nYour string is : "+str);
int count = 0;
while(string_matcher.find()) {
count = count + 1;
System.out.println("\tposition "+string_matcher.start() +": "+ str.charAt(string_matcher.start()));
}
System.out.println("\nThere are "+count+" special characters");
System.out.println("\n\t------------------------------------");
}
}
Code Explanation
1. Pattern Definition
Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE)
This regex pattern [^a-z0-9 ] matches any character that is NOT a letter (a-z), number (0-9), or space.
2. Matcher Usage
Matcher string_matcher = string_patterns.matcher(str)
The matcher is created to find all occurrences of the pattern in the input string.
3. Finding Special Characters
while(string_matcher.find()) {
count = count + 1;
System.out.println("\tposition "+string_matcher.start() +": "+ str.charAt(string_matcher.start()));
}
The find() method returns true each time a match is found, and start() returns the position of the match.
Key Concepts
Regex Pattern
[^a-z0-9 ] is a negated character class that matches anything except letters, digits, and spaces.
Matcher.find()
Returns true if the pattern is found in the string and advances the matcher to the next match.
Matcher.start()
Returns the start position of the previous match in the string.
Pattern.CASE_INSENSITIVE
Flag to make pattern matching case-insensitive, covering both uppercase and lowercase letters.
Sample Outputs
Output 1: String with Special Characters
Enter a string : `Welcome to #coderwebsite && "j@v@" is @m@zing programming l@ngu@ge`!
______________ OUTPUT ______________
Your string is : `Welcome to #coderwebsite && "j@v@" is @m@zing programming l@ngu@ge`!
position 0: `
position 12: #
position 26: &
position 27: &
position 29: "
position 31: @
position 33: @
position 34: "
position 39: @
position 41: @
position 60: @
position 64: @
position 67: `
position 68: !
There are 14 special characters
------------------------------------
Output 2: String without Special Characters
Enter a string : Welcome to coderwebsite
______________ OUTPUT ______________
Your string is : Welcome to coderwebsite
There are 0 special characters
------------------------------------
Use Cases
- Data Validation: Check if user input contains invalid special characters
- Password Validation: Ensure passwords contain or don't contain certain characters
- Text Sanitization: Identify and remove special characters from text
- Security Checks: Detect potentially malicious input or SQL injection attempts
Summary
This program effectively demonstrates how to use Java's regex capabilities to find and count special characters in a string. The key is using a negated character class [^a-z0-9 ] to match anything that isn't a letter, digit, or space.
By combining Pattern and Matcher classes, you can efficiently process strings and extract specific information based on complex patterns.