FOR FREE YEAR SOLVED

Frequency of each character in a string

Back to Programming

Description

Count frequency of each character in a given string: 

 

In this program, a string is taken as input, and then count the frequency of each character is counted and printed. The frequency of each character means how many times the character has occurred in the string.

 

For example: 

Let the input string be- i am a good girl.

 

The output after executing this program-

The frequency of ‘i’ is 2

The frequency of ' ' is  4

The frequency of 'a' is  2

The frequency of 'm' is 1

The frequency of 'g' is  2

The frequency of 'o' is  2

The frequency of 'd' is  1

The frequency of 'r' is  1

The frequency of 'l' is  1

 

For executing this program, each character is fetched individually from the string and then the string is traversed from its next character and all the traversed character is compared. If there is any matching then the counter is incremented by 1. If the frequency of any character is already calculated then it is substituted by null value to remove the duplicity of the characters

Algorithm

INPUT: A String
OUTPUT: The frequency of each character
PROCESS:
Step 1: [Taking the input]
	Read str [the input string]
Step 2: [Counting the frequency of each character]
	Set c<-0
Set n<-length (str)
[converting the string into lower case]
For i=0 to n-1 repeat
If str[i]≥'A' and str[i]≤'Z' then
Set str[i]<-str[i]+32
		[End of ‘if’]
	[End of ‘for’ loop]
   	[counting the frequency of the elements]
    	For i=0 to n-1 repeat
        Set c<- 1
        If str[i]≠’\0’ then        	
For j=i+1 to n-1 repeat        	
        			If str[i]=str[j]
        				Set c<-c+1
        				Set str[j]<-'\0'
			[End of ‘if’]
		[End of ‘for’ loop]
		Print "The frequency of str[i] is c”.
	         [End of ‘if’]
	[End of ‘for’ loop]

Step 3: Stop.

Code

Time Complexity:

The time complexity of this program is O(n2) where ‘n’ is the number of characters of the string.

 

Space Complexity:

The space complexity of this program is O(n) where ‘n’ is the number of characters of the string.

Contributed by