欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 新车 > 用C语言编写一个函数

用C语言编写一个函数

2024/10/25 13:17:07 来源:https://blog.csdn.net/2302_76708905/article/details/142964719  浏览:    关键词:用C语言编写一个函数

输出给定的字符串中字母、数字、空格和其他字符的个数

(1)编写main函数

#include <stdio.h>int main() {return 0;
}

(2)编写计数函数

#include <stdio.h>void count_chars(char *str) {int letters = 0; // 字母计数器int digits = 0; // 数字计数器int spaces = 0; // 空格计数器int others = 0; // 其他字符计数器// 判断并计数for (int i = 0; str[i] != '\0'; ++i) {if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z')) {letters++;} else if (str[i] >= '0' && str[i] <= '9') {digits++;} else if (str[i] == ' ') {spaces++;} else {others++;}}// 输出各种字符的个数printf("Letters:%d\n", letters);printf("Digits:%d\n", digits);printf("Spaces:%d\n", spaces);printf("Others:%d\n", others);
}int main() {return 0;
}

(3)编写main函数

#include <stdio.h>void count_chars(char *str) {int letters = 0; // 字母计数器int digits = 0; // 数字计数器int spaces = 0; // 空格计数器int others = 0; // 其他字符计数器// 判断并计数for (int i = 0; str[i] != '\0'; ++i) {if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z')) {letters++;} else if (str[i] >= '0' && str[i] <= '9') {digits++;} else if (str[i] == ' ') {spaces++;} else {others++;}}// 输出各种字符的个数printf("Letters:%d\n", letters);printf("Digits:%d\n", digits);printf("Spaces:%d\n", spaces);printf("Others:%d\n", others);
}int main() {char str[30];printf("Please enter the value of str: ");fgets(str, sizeof(str), stdin); // 使用 fgets 读取整行输入count_chars(str);return 0;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com