Frequently Asked Java Program 21: Java Program to Find & Print All Special Characters with Their Positions in a String

This programming interview question was asked in Yodlee. 

Problem: Write a Java program to find and print all special characters with their positions in a user input string.

Example:
Input string: Make%Selenium$Easy#

Output:
% at position 5.
$ at position 14.
# at position 19.
Total special characters found:3

Solution:
We will use regex to find known special characters in a given string.

Java Program:

package StringPrograms;

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



public class SpecialChars {

	public static void main(String[] args) {

		// User input to find special characters 
		Scanner sc = new Scanner(System.in);
		System.out.println("Please enter the string to find special characters:");

		String userInput = sc.nextLine();

		sc.close();

		System.out.println("You entered: " + userInput);

		

        // We know there are 33 special characters. So we will use them.
		Pattern p = Pattern.compile("[ !\"#$%&'()*+,-./:;<=>?@\\[\\]^_`{|}~]");
		Matcher m = p.matcher(userInput);
		
		// Iterating matcher
		int countOfSplChars = 0;
		while (m.find()) {
			countOfSplChars += 1;
			System.out.println(userInput.charAt(m.start())+ " at position " + (m.start()+1)+ ".");
		}
		System.out.println("Total special characters found:"+countOfSplChars);
	}
}

Output:

Please enter the string to find special characters:
Make%Selenium$Easy#
You entered: Make%Selenium$Easy#
% at position 5.
$ at position 14.
# at position 19.
Total special characters found:3

#HappyCoding

Author: Amod Mahajan

My name is Amod Mahajan and I am an IT employee with 4+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went throw so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning