分类统计各类字符个数
时间: 2024-01-20 19:14:58 浏览: 72
以下是分类统计各类字符个数的示例代码:
```c
#include <stdio.h>
#include <ctype.h>
void StringCount(char *s) {
int upper = 0, lower = 0, space = 0, digit = 0, other = 0;
while (*s != '\0') {
if (isupper(*s)) {
upper++;
} else if (islower(*s)) {
lower++;
} else if (*s == ' ') {
space++;
} else if (isdigit(*s)) {
digit++;
} else {
other++;
}
s++;
}
printf("%d %d %d %d %d", upper, lower, space, digit, other);
}
```
该函数接收一个字符串指针作为参数,然后遍历整个字符串,统计其中大写字母、小写字母、空格、数字以及其它字符的个数,并按照 大写字母个数 小写字母个数 空格个数 数字个数 其它字符个数 的格式输出。
相关问题
分类统计各类字符个数C语言
下面是一个简单的 C 代码片段,用于统计给定字符串中每个字符类型(字母、数字、空格等)的出现次数。
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char string[100];
int i, alphabets=0, digits=0, spaces=0, punctuations=0;
printf("Enter a string: ");
fgets(string, sizeof(string), stdin);
for(i=0;string[i]!='\0';i++) {
if(isalpha(string[i]))
alphabets++;
else if(isdigit(string[i]))
digits++;
else if(isspace(string[i]))
spaces++;
else
punctuations++;
}
printf("Alphabets = %d\n", alphabets);
printf("Digits = %d\n", digits);
printf("Spaces = %d\n", spaces);
printf("Punctuations = %d\n", punctuations);
return 0;
}
```
该代码使用了 `ctype.h` 头文件中的函数来检查每个字符。`isalpha()` 函数用于检查字母,`isdigit()` 函数用于检查数字,`isspace()` 函数用于检查空格,而其他字符则被认为是标点符号。通过循环遍历输入的字符串并计算每个字符类别的出现次数,最终将结果打印出来。
在Vc环境下分类统计各类字符个数
在VC环境下,可以使用以下方法来分类统计各类字符个数:
```c++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
// 打开文件
ifstream fin("input.txt");
if (!fin) {
cerr << "无法打开文件" << endl;
return 1;
}
// 统计字符个数
int count[128] = { 0 };
char ch;
while (fin.get(ch)) {
if (ch >= 0 && ch <= 127) {
count[ch]++;
}
}
// 输出结果
for (int i = 0; i < 128; i++) {
if (count[i] > 0) {
cout << (char)i << ": " << count[i] << endl;
}
}
// 关闭文件
fin.close();
return 0;
}
```
这段代码会打开一个名为"input.txt"的文本文件,并统计其中出现的各类字符的个数。最后,程序会输出结果,格式为"字符: 个数"。请注意,由于本程序使用的是ASCII码,因此只能统计ASCII码范围内(即0~127)的字符。如果需要统计更多字符,需要使用更高级的字符编码。
相关推荐
![](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)
![](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)