用c++代码编程计算一行字符字母,数字字符,其他字符出现的个数,并按照从小到大排序
时间: 2024-05-24 17:11:49 浏览: 47
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAX_LEN 100
void count_chars(char *str, int len, int *alpha, int *digit, int *other) {
int i;
for (i = 0; i < len; i++) {
if (isalpha(str[i])) {
(*alpha)++;
} else if (isdigit(str[i])) {
(*digit)++;
} else {
(*other)++;
}
}
}
void sort_counts(int *alpha, int *digit, int *other) {
int counts[3] = {*alpha, *digit, *other};
int i, j;
for (i = 0; i < 2; i++) {
for (j = i + 1; j < 3; j++) {
if (counts[i] > counts[j]) {
int temp = counts[i];
counts[i] = counts[j];
counts[j] = temp;
}
}
}
*alpha = counts[0];
*digit = counts[1];
*other = counts[2];
}
int main() {
char str[MAX_LEN];
int len, alpha = 0, digit = 0, other = 0;
printf("Enter a string:\n");
fgets(str, MAX_LEN, stdin);
len = strlen(str);
count_chars(str, len, &alpha, &digit, &other);
sort_counts(&alpha, &digit, &other);
printf("Alphabets: %d\n", alpha);
printf("Digits: %d\n", digit);
printf("Other characters: %d\n", other);
return 0;
}
阅读全文