Given a string, our task is finding the occurrence of a character in the string with the help of user-defined function.
Example: Input : "hello" Output : h occur 1 times e ocuur 1 times l occur 2 times o occur 1 times Explanation : here "hello" have 1 h, so it have 1 value. as same e have 1, l have 2 , o have 1. Example 2: Input : "did" Output: d occur 2 times i occur 1 times
Approach 1: In this approach we use a map data structure to store the number of times characters occur.
- First we initialize map with key each character of string and value for each is 0.
- We iterate over string and increment value of the character.
- Finally, print key-values of the map.
h ocuurs 1 times e ocuurs 1 times l ocuurs 3 times o ocuurs 2 times w ocuurs 1 times r ocuurs 1 times d ocuurs 1 times
Approach 2: In this approach, we use nested for loop to iterate over string and count for each character in the string.
- First initialize count with value 0 for ith value of string.
- Now we iterate over string if ith value matches with the character, increase the count value by 1.
- Finally, print the value of count.
g occurs 2 times f occurs 1 times h occurs 1 times e occurs 1 times l occurs 2 times o occurs 1 times