Make Selenium Easy

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

A software Tester who is paid to judge products developed by others. Currently getting paid in American Dollars. Writing technical posts and creating YouTube videos are my hobbies.

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

Please wait...

Subscribe to new posts to become automation expert

Want to be notified when my new post is published? Get my posts in your inbox.