Frequently Asked Java Program 30: Java Program to Find Distinct Characters In Given String

Hello Folks,

As part of Frequently Asked Java Programs In Interviews For Freshers And Experienced, in this post we will see a java program to Find Distinct Characters In Given String.

Problem Statement:

User input: Make Selenium Easy

Output: K L N I U Y

Problem Solution: 

Logic:

  1. Convert input string in to same case either upper or lower.
  2. Replace all whitespace with empty space. 
  3. Take first char from given String.
  4. lastIndexOf(char c) method of String class gives the index of last occurrence of char in given string. If a character is not repeated in given string,  lastIndexOf should give zero as we took first char to check. If it is zero, print.
  5. To repeat step 3 and 4, we must need to replace already checked char from string with empty space.

Java Program:

package StringPrograms;

import java.util.Scanner;

public class FindDistinctCharInString {

	public static void findPrintDistinctCharInString(String inputString) {

		// Converting input string to upper case
		inputString = inputString.toUpperCase();
		
		// Removing all white spaces
		inputString = inputString.replace(" ", "");

		// We need to keep counting char till its length is greater than 0
		while (inputString.length() > 0) {
			// Extracting first char
			char c = inputString.charAt(0);
			/*
			 * lastIndexOf(char c) method of String class gives the index of last occurrence of char in given string. 
			 * If a character is not repeated in given string,  lastIndexOf should give zero as we took first char to check. 
			 * If it is zero, print.
			 */
			if(inputString.lastIndexOf(c)==0)
				System.out.print(c+" ");
	
			// Remove char whose occurrence is checked
			inputString = inputString.replace(Character.toString(c), "");
		}
		

	}

	public static void main(String[] args) {

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

		String userInput = sc.nextLine();

		sc.close();

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

		findPrintDistinctCharInString(userInput);
	}

}

Output:

Please enter the string to find distinct characters:
Make Selenium Easy
You entered: Make Selenium Easy
K L N I U Y

Run program for multiple inputs and let me know if it fails. Comment if you have better approach. If you like my posts please like, comment and share to reach it to maximum.

#HappyCoding

Leave a Reply

Your email address will not be published. Required fields are marked *