编写一个函数找出字符串中某个特定字符出现的次数 不使用count 方法
时间: 2023-11-12 14:28:32 浏览: 64
好的,以下是一个可以找出字符串中某个特定字符出现的次数的函数,它不使用 count 方法:
```python
def count_char(string, char):
count = 0
for i in string:
if i == char:
count += 1
return count
```
你可以调用这个函数来查找字符串中某个字符出现的次数。例如,如果你想要查找字符串 "hello world" 中字母 "l" 出现的次数,可以这样调用:
```python
count = count_char("hello world", "l")
print(count) # 输出 3
```
希望这个函数能够满足你的需求。
相关问题
Python,下面的函数头,编写一个函数找出字符串中某个特定字符 出现次数 def count(s,ch):
好的,下面是代码实现:
```python
def count(s, ch):
"""
统计字符串s中特定字符ch出现的次数
:param s: 待统计的字符串
:param ch: 特定字符
:return: 出现次数
"""
count = 0
for i in s:
if i == ch:
count += 1
return count
```
这个函数会遍历整个字符串,每当遇到与特定字符相同的字符,计数器就加一。最终,函数会返回特定字符在字符串中出现的次数。
使用下面的函数头,编写一个函数找出字符串中某个特定字符的出现次数。要求不使用string类提供的 count 方法。编写程序实现提示用户输入一个字符串,然后再输人一个字符,调用该函数显示该字符在字符串中出现的次数,
函数头如下:
```c++
int countChar(const char* str, char c);
```
函数实现如下:
```c++
#include <iostream>
int countChar(const char* str, char c) {
int count = 0;
for(int i = 0; str[i] != '\0'; ++i) {
if(str[i] == c) {
++count;
}
}
return count;
}
int main() {
char str[100];
char c;
std::cout << "请输入一个字符串: ";
std::cin >> str;
std::cout << "请输入一个字符: ";
std::cin >> c;
int count = countChar(str, c);
std::cout << "该字符在字符串中出现了 " << count << " 次" << std::endl;
return 0;
}
```
该程序首先提示用户输入一个字符串和一个字符,然后调用 countChar 函数计算该字符在字符串中出现的次数,并输出结果。需要注意的是,该程序仅适用于单个字符的计数,如果需要计算字符串中某个子串出现的次数,可以使用类似的方式遍历字符串。
相关推荐
![](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)