📅  最后修改于: 2023-12-03 15:37:14.750000             🧑  作者: Mango
The International Space Research Organization (ISRO) is a government space agency of India that is responsible for the development of satellite technology, remote sensing, and space science. The ISRO CS 2011 Question 40 is a programming question that requires the programmer to write a function that determines the number of times a given character appears in a string.
Write a function called count_char()
that takes in two arguments: a string and a character. The function should return the number of times the character appears in the string.
def count_char(string, char):
# your code here
string = 'Hello World!'
char = 'l'
print(count_char(string, char))
3
string = 'ISRO CS 2011 Question 40'
char = ' '
print(count_char(string, char))
4
To count the number of times a character appears in a string, we can loop through each character in the string and check if it matches the given character. We can use a counter variable to keep track of the number of matches found. Here is a possible implementation:
def count_char(string, char):
count = 0
for c in string:
if c == char:
count += 1
return count
We can test the function with the sample input/output given in the problem statement:
string = 'Hello World!'
char = 'l'
print(count_char(string, char)) # 3
string = 'ISRO CS 2011 Question 40'
char = ' '
print(count_char(string, char)) # 4
We can also test the function with some edge cases, such as an empty string or a string with only the given character:
string = ''
char = 'a'
print(count_char(string, char)) # 0
string = 'a'*10
char = 'a'
print(count_char(string, char)) # 10
The ISRO CS 2011 Question 40 is a simple programming exercise that tests the programmer's ability to write a function that counts the number of times a character appears in a string. With this problem, we have demonstrated how to use a loop and a counter variable to solve the problem in Python.