2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > 输入一行字符统计英文字母 空格 数字和其他字符的个数

输入一行字符统计英文字母 空格 数字和其他字符的个数

时间:2020-02-19 13:09:53

相关推荐

输入一行字符统计英文字母 空格 数字和其他字符的个数

使用c语言的三种循环分别写出输入一行字符统计英文字母,空格,数字和其他字符的个数的代码如下:

**1. for循环实现**

```c

#include <stdio.h>

int main()

{

char str[100];

int i, alphabets, digits, spaces, others;

alphabets = digits = spaces = others = 0;

printf("请在此输入字符串: ");

fgets(str, sizeof(str), stdin);

for (i = 0; str[i] != '\0'; i++)

{

if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z'))

{

alphabets++;

}

else if (str[i] >= '0' && str[i] <= '9')

{

digits++;

}

else if (str[i] == ' ')

{

spaces++;

}

else

{

others++;

}

}

printf("字母数量: %d\n", alphabets);

printf("数字数量: %d\n", digits);

printf("空格数量: %d\n", spaces);

printf("其他字符数量: %d\n", others);

return 0;

}

```

**2. while循环实现**

```c

#include <stdio.h>

int main()

{

char str[100];

int i, alphabets, digits, spaces, others;

alphabets = digits = spaces = others = 0;

printf("请在此输入字符串: ");

fgets(str, sizeof(str), stdin);

i = 0;

while (str[i] != '\0')

{

if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z'))

{

alphabets++;

}

else if (str[i] >= '0' && str[i] <= '9')

{

digits++;

}

else if (str[i] == ' ')

{

spaces++;

}

else

{

others++;

}

i++;

}

printf("字母数量: %d\n", alphabets);

printf("数字数量: %d\n", digits);

printf("空格数量: %d\n", spaces);

printf("其他字符数量: %d\n", others);

return 0;

}

```

**3. do-while循环实现**

```c

#include <stdio.h>

int main()

{

char str[100];

int i, alphabets, digits, spaces, others;

alphabets = digits = spaces = others = 0;

printf("请在此输入字符串: ");

fgets(str, sizeof(str), stdin);

i = 0;

do

{

if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z'))

{

alphabets++;

}

else if (str[i] >= '0' && str[i] <= '9')

{

digits++;

}

else if (str[i] == ' ')

{

spaces++;

}

else

{

others++;

}

i++;

} while (str[i] != '\0');

printf("字母数量: %d\n", alphabets);

printf("数字数量: %d\n", digits);

printf("空格数量: %d\n", spaces);

printf("其他字符数量: %d\n", others);

return 0;

}

```

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。