Find and display occurrence of each chracter in a string. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Find and display occurrence of each chracter in a string.

Input : a string that contains several characters. Output : Frequency (number of times each chracter occurred) of each chracter that is present in the given string. Sample input : Solo learn Output : s : 1 o : 2 l : 2 e : 1 a : 1 r : 1 n : 1

29th Oct 2020, 7:41 PM
Ameer Haider
Ameer Haider - avatar
4 Answers
+ 5
intialize an empty object like, string_occurence={}. Now loop over the string =>for(item of string) Then check If that item is already in object =>if (string_occurence[item] ),if yes increment it by one else assign object key with a value of one => string_occurence[item]=1 Finally you can use the following loop with Object.entries method and Some destructuring to print out the items in object for(const [i,j] of Object.entries(string_occurrence)).. Hopefully this helps ,
29th Oct 2020, 8:12 PM
Abhay
Abhay - avatar
+ 4
Use a Map object or build a dictionary object to store key, value pairs. Use the character as the key. If the character is in the Map object, increment its value by 1 for each time the character repeats in the string otherwise add it to the Map object and set its initial value to 1. Then loop through the Map and output its elements. https://javascript.info/map-set
29th Oct 2020, 7:57 PM
ChaoticDawg
ChaoticDawg - avatar
+ 2
So what is your question like where you stuck at and need help ?
29th Oct 2020, 7:51 PM
Abhay
Abhay - avatar
0
how can i find frequency of each chracter in a given string..?
29th Oct 2020, 7:53 PM
Ameer Haider
Ameer Haider - avatar