编写函数统计并输出某串中指定字符串的个数
时间: 2024-05-05 22:15:36 浏览: 21
以下是Python的代码实现:
```python
def count_substring(string, sub):
"""
统计字符串 string 中子串 sub 的个数
"""
count = 0
start = 0
while True:
idx = string.find(sub, start)
if idx == -1:
break
count += 1
start = idx + 1
return count
```
函数接受两个参数:字符串 `string` 和子串 `sub`,返回子串在字符串中出现的个数。
函数中使用了 `find()` 方法查找子串在字符串中的位置。如果找不到子串,`find()` 方法会返回 -1。在每次找到子串后,将计数器加一,并将查找的起始位置往后移动一位。如果找不到子串了,就退出循环并返回计数器的值。
例如,如果要统计字符串 `"hello, world"` 中子串 `"o"` 的个数,可以调用函数:
```python
count_substring("hello, world", "o") # 返回 2
```
相关问题
C语言编写函数fun,统计字符串中指定字符的个数。
可以这样写:
```c
int fun(char *str, char ch) {
int count = 0;
while (*str != '\0') {
if (*str == ch) {
count++;
}
str++;
}
return count;
}
```
其中,`str`是输入的字符串,`ch`是要统计的字符,函数返回这个字符在字符串中出现的次数。
函数的实现很简单,就是遍历字符串的每一个字符,如果遇到和要统计的字符相同的字符,就将计数器加1。最后返回计数器的值即可。
C语言编写函数统计一个字符串中英文字母的个数
可以使用C语言中的字符处理库函数`isalpha()`来判断一个字符是否是字母,然后遍历字符串,统计字母个数即可。下面是一个示例函数:
```c
#include <ctype.h>
int count_letters(char *str) {
int count = 0;
for (int i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) {
count++;
}
}
return count;
}
```
函数`count_letters()`接受一个字符串指针作为参数,返回字符串中字母的个数。函数内部遍历字符串中的每个字符,如果是字母则计数器加1。最后返回计数器的值。注意需要在文件开头包含`ctype.h`头文件,以使用`isalpha()`函数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)