# 示例代码:查找字符串中指定字符出现的次数
def count_occurrences(input_string, char_to_find):
"""
函数用于计算指定字符在字符串中出现的次数。
参数:
input_string (str): 要查找的字符串。
char_to_find (str): 要查找的字符。
返回:
int: 指定字符在字符串中出现的次数。
"""
count = 0
for char in input_string:
if char == char_to_find:
count += 1
return count
# 示例用法
input_string = "hello world"
char_to_find = "l"
result = count_occurrences(input_string, char_to_find)
print(f"字符 '{char_to_find}' 在字符串 '{input_string}' 中出现了 {result} 次。")
定义函数 count_occurrences
:
input_string
(要查找的字符串)和 char_to_find
(要查找的字符)。初始化计数器 count
:
遍历字符串:
for
循环遍历字符串中的每个字符,如果当前字符等于要查找的字符,则将计数器加1。返回结果:
示例用法:
input_string
和要查找的字符 char_to_find
,调用 count_occurrences
函数并打印结果。上一篇:rpa for python
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站