用C语言指针编辑一个函数,功能:用户输入一行字符串,统计此字符串中每一个小写字母出现的次数,并分别打印
时间: 2024-03-14 22:47:49 浏览: 75
好的,以下是一个使用指针实现上述功能的 C 语言函数:
```c
#include <stdio.h>
void count_lowercase(char *str) {
int counts[26] = {0}; // 用于统计每个小写字母出现的次数,初始值为 0
// 遍历字符串中的每个字符
while (*str != '\0') {
char c = *str;
if (c >= 'a' && c <= 'z') { // 如果该字符是小写字母
counts[c - 'a']++; // 统计该字母出现的次数
}
str++;
}
// 打印每个小写字母出现的次数
for (int i = 0; i < 26; i++) {
if (counts[i] > 0) { // 只打印出现过的字母
printf("%c: %d\n", 'a' + i, counts[i]);
}
}
}
```
使用方法同上,只需要在 `main` 函数中调用 `count_lowercase` 函数并传入一个指向输入字符串的指针即可。
需要注意的是,在本例中,我们使用了指针来遍历输入字符串。具体而言,我们使用一个指向输入字符串的指针 `str`,并在每次循环中将其指向下一个字符,直到遍历完整个字符串。然后,我们仍然可以像之前一样使用数组来统计每个小写字母出现的次数。
相关问题
用C语言编写自定义函数实现以下功能:把字符串中所有的字母改写成该字母的下一个字母,字母z改写成字母 a。大写字母仍为大写字母,小写字母仍为小写字母,其它的字符不变。转换过程在自定义函数中完成,在主函数中输入字符串并输出结果。
下面是用C语言编写的实现代码:
```c
#include <stdio.h>
#include <ctype.h>
void convert(char *str);
int main()
{
char str[100];
printf("请输入一个字符串:");
fgets(str, 100, stdin);
convert(str);
printf("转换后的字符串为:%s", str);
return 0;
}
void convert(char *str)
{
while(*str)
{
if(isalpha(*str))
{
if(*str == 'z' || *str == 'Z')
{
*str = *str - 25;
}
else
{
*str = *str + 1;
}
}
str++;
}
}
```
在这个程序中,我们定义了一个 `convert()` 函数,它接受一个字符串作为参数并修改该字符串以进行转换。
首先,我们使用 `while(*str)` 循环遍历整个字符串。然后,我们使用 `isalpha()` 函数检查当前字符是否是字母。如果是,我们检查它是否是字母 z 或 Z,如果是,我们将其转换为 a 或 A,否则将该字符加 1。最后,我们将指针 `str` 向前移动一位,以便处理下一个字符。
在主函数中,我们使用 `fgets()` 函数从标准输入读取一个字符串,并将其传递给 `convert()` 函数进行转换。最后,我们输出转换后的字符串。
编写C语言程序,实现的功能是:统计一个字符串中大写字母、小写字母、数字和其他字符的个数,用指针实现
好的,下面是实现代码:
```c
#include <stdio.h>
#include <ctype.h>
void count_chars(char *str, int *upper, int *lower, int *digit, int *other) {
while (*str) {
if (isupper(*str)) {
(*upper)++;
} else if (islower(*str)) {
(*lower)++;
} else if (isdigit(*str)) {
(*digit)++;
} else {
(*other)++;
}
str++;
}
}
int main() {
char str[100];
int upper = 0, lower = 0, digit = 0, other = 0;
printf("请输入一个字符串:");
fgets(str, 100, stdin);
count_chars(str, &upper, &lower, &digit, &other);
printf("大写字母:%d\n小写字母:%d\n数字:%d\n其他字符:%d\n", upper, lower, digit, other);
return 0;
}
```
在这个程序中,我们定义了一个名为 `count_chars` 的函数来统计字符串中各种字符的个数。该函数使用了指针来传递 `upper`、`lower`、`digit` 和 `other` 四个变量的地址,以便在函数内部修改它们的值。
在 `main` 函数中,我们首先读入一个字符串,然后调用 `count_chars` 函数来统计其中各种字符的个数,并最终输出结果。
注意,我们在处理字符时使用了 `ctype.h` 中的函数,这些函数可以判断字符是否为大写字母、小写字母或数字。
阅读全文
相关推荐













