用c语言写求ss所指字符串中指定字符的个数
时间: 2024-03-06 09:51:34 浏览: 33
可以使用如下的C语言代码实现:
```c
#include <stdio.h>
#include <string.h>
int count_char(const char *str, char c) {
int count = 0;
for (int i = 0; i < strlen(str); i++) {
if (str[i] == c) {
count++;
}
}
return count;
}
int main() {
char ss[] = "hello, world!";
char c = 'l';
int count = count_char(ss, c);
printf("The count of '%c' in '%s' is %d\n", c, ss, count);
return 0;
}
```
在这个程序中,我们首先定义了一个 `count_char` 函数,该函数用于计算字符串中指定字符的个数。函数接收两个参数,第一个参数 `str` 表示要查找的字符串,第二个参数 `c` 表示要计算的字符。函数内部使用了一个循环来遍历字符串中的每个字符,如果当前字符等于指定字符,则计数器 `count` 加 1。最后函数返回计数器的值。
在 `main` 函数中,我们定义了一个字符串 `ss` 和一个字符 `c`,然后调用 `count_char` 函数来计算字符串 `ss` 中字符 `c` 的个数,并将结果打印出来。
相关问题
编写函数fun求ss所指字符串中指定字符的个数,并返回此值
根据您的描述,我编写了以下的C语言代码来实现您的要求:
```c
int fun(char *ss, char ch){
int count = 0;
while(*ss != '\0'){
if(*ss == ch){
count++;
}
ss++;
}
return count;
}
```
这个函数的作用是在`ss`所指的字符串中查找`ch`这个字符,并返回它在字符串中出现的次数。它使用了一个`while`循环来遍历整个字符串,如果当前字符等于`ch`,则把计数器`count`加1。最终返回`count`的值即可。
注意,这个函数假设输入的字符串以`\0`结尾,如果不是这样的话,可能会导致程序出错。
c语言编程 请编写函数fun,它的功能是:求出ss所指字符串中指定字符的个数,并返回此值。
```c
int fun(char *ss, char c) {
int count = 0;
while (*ss != '\0') {
if (*ss == c) {
count++;
}
ss++;
}
return count;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)