Frequently Asked Java Program 26: Java Program to Find Occurrence of Each Char in a Given String Without Using Collection

Problem Statement:

Write a program to print occurrence of each character in given string without using Collection.

Example:-

Please enter the string to find occurrence of each char:
Make Selenium Easy
You entered: Make Selenium Easy
Occurrence of M : 2
Occurrence of A : 2
Occurrence of K : 1
Occurrence of E : 4
Occurrence of whitespace : 2
Occurrence of S : 2
Occurrence of L : 1
Occurrence of N : 1
Occurrence of I : 1
Occurrence of U : 1
Occurrence of Y : 1

Problem Solution:

This problem is easy to solve with the help of Collection framework of Java but in interview, you might be asked to solve without using Collection framework.

Logic:

  1. We will pick first char from given string and iterate through each char of String to match if same char is present. We will use a counter with default value as zero for each iteration. Counter will be incremented by one if occurrence of char is found.
  2. We will replace the char with empty char at end of each iteration causing reduction in length of actual string.  Iteration will be continued till the length of String is greater than one.
  3. When (If) length of string is equal to 1, print occurrence of last char  as one.
  4. We will give name to whitespace (” “) as “Whitespace” for better readability of output.

Java Programs:

 

Output:

Please enter the string to find occurrence of each char:
Make Selenium Easy
You entered: Make Selenium Easy
Occurrence of M : 2
Occurrence of A : 2
Occurrence of K : 1
Occurrence of E : 4
Occurrence of whitespace : 2
Occurrence of S : 2
Occurrence of L : 1
Occurrence of N : 1
Occurrence of I : 1
Occurrence of U : 1
Occurrence of Y : 1
==============================================================
Please enter the string to find occurrence of each char:
ABCDEF
You entered: ABCDEF
Occurrence of A : 1
Occurrence of B : 1
Occurrence of C : 1
Occurrence of D : 1
Occurrence of E : 1
Occurrence of F : 1
===============================================================

#HappyCoding

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

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.
%d bloggers like this: