编写一个自定义函数intcountchar(char*p,charch),实现统计p所指向的字符串?

如题所述

#include <stdio.h>
int countchar(char *p, char ch) {
int count = 0;

while (*p != '\0') {
if (*p == ch) {
count++;
}
p++;
}

return count;
}
int main() {
char str[] = "Hello World!";
char ch = 'o';
int result = countchar(str, ch);

printf("The character '%c' appears %d times in the string.\n", ch, result);

return 0;
}
在上面的代码中,countchar函数接受一个指向字符串的指针p和一个字符ch作为参数。函数使用一个循环遍历字符串中的每个字符,如果字符与指定字符相等,则将计数器count递增。最后,函数返回计数器的值。
在main函数中,我们定义了一个字符串str和一个字符ch,然后调用countchar函数,并将结果打印出来。
请注意,上述代码仅为示例,可能需要根据具体的需求进行调整。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2023-05-30
/*
利用指向函数的指针变量写一个函数int count1(char *p),
统计输入字符串中的小写字母的个数。
在main函数中输入字符串,并输出统计结果。
附加:再编写一个函数int count2(char *p),
统计输入字符串中的数字的个数,在主函数中输入1,
执行count1函数,输入2,执行count2函数。
(同一个指针指向不同的函数)
//
c语言实现 visual studio 2010编译通过
编码:字符集UNICODE
*/
//#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string>
using namespace std;
int count1(char *p);
int count2(char *p);
void fnMenu();
void fnInputString(char *p);
//如果不是在VS平台,请用int main(int argc, char* argv[])
int _tmain(int argc, _TCHAR* argv[])
{
char str[1204];
//
fnMenu();
//
while(1)
{
switch(getchar())
{
case '1':
printf("小字母个数是:%d\n",count1(str));
printf("请输入菜单选项:");
break;
case '2':
printf("数字个数是:%d\n",count2(str));
printf("请输入菜单选项:");
break;
case '3':
system("cls");
fnMenu();
break;
case '9':
fnInputString(str);
break;
case '0':
exit(0);
break;
default:break;
}
}
return 0;
}
int count1(char *p){
int iLowAlpha = 0;
for(int i= 0;p[i] != '\0';i++)
{
if(p[i] >= 'a' &&p[i] <= 'z')
{
iLowAlpha++;
}
}
return iLowAlpha;
}
int count2(char *p){
int iDigital = 0;
for(int i= 0;p[i] != '\0';i++)
{
if(p[i] >= '0' && p[i] <= '9')
iDigital++;
}
return iDigital;
}
void fnInputString(char *p){
printf("请输入字符串:");
scanf("%s",p); //此处不能用scanf_s
printf("请输入菜单选项:");
}
void fnMenu(){
printf(" 统计小写字母个数 \n");
printf(" **********************************************\n");
printf(" ****** 菜单选项 ******\n");
printf(" ****** ******\n");
printf(" ****** 9.输入字符串 ******\n");
printf(" ****** 1.输出小写字母个数 ******\n");
printf(" ****** 2.输出数字个数 ******\n");
printf(" ****** 3.清屏 ******\n");
printf(" ****** 0.退出 ******\n");
printf(" ****** ******\n");
printf(" **********************************************\n");
printf("请输入菜单选项:");
}
相似回答
大家正在搜