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.

Input string: Make%Selenium$Easy#

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

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.out.println("Please enter the string to find special characters:");

		String userInput = sc.nextLine();


		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);


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


Author: Amod Mahajan

My name is Amod Mahajan and I am an IT employee with 6+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went through 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

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

  1. Program is very good !!!!

    But we need some more explain which were you given like other programs. In this I don’t see any explanation before starting the program .Because this could be helpful beginner level peoples.

Leave a Reply