Table of Contents

Count Occurrences of a Character in a String

Example Description
This code will prompt user to enter a string and a character, then it will display the number of occurrences of that character in the string.

Introduction:

In this code, we have a function called charCount() that takes two parameters: ch (the character to be counted) and st (the string in which we want to count the occurrences of the character). The function uses a for loop to iterate through each character in the string. If the character matches the character we are searching for, the count variable is incremented. Finally, the function returns the count. The main part of the code prompts the user to enter a string and a character, calls the charCount() function, and then displays the result.

Code:

#Function to count the number of times a character occurs in a 
#string
def charCount(ch,st):
 count = 0
 for character in st:
  if character == ch:
    count += 1
 return count
#end of function
st = input("Enter a string: ")
ch = input("Enter the character to be searched: ")
count = charCount(ch,st)
print("Number of times character",ch,"occurs in the string is:",count)

Logic:

  1. The code takes an input string and a character from the user.
  2. It then calls the charCount() function with these inputs.
  3. The charCount() function counts the number of times the given character occurs in the string using a for loop.
  4. If the character matches the given character, the count variable is incremented.
  5. Finally, the count is returned and displayed as the output.

Output:

Enter a string: Hello World

Enter the character to be searched: o

>> Number of times character o occurs in the string is: 2