1,1标准输入读入字符,统计各类字符所占百分比
#include <stdio.h> #include <ctype.h> //不可打印字符 int isunprint(int ch){ return !isprint(ch); } //转换表,储存各个判断函数指针 int (*tables[])(int) = {iscntrl, isspace, isdigit, islower, isupper, ispunct, isunprint}; int main() { int count[7] = {0}; int ch; int idx; while((ch = getchar()) != EOF){ //转换表中的函数进行测试,如果符合对应的数组项+1 for(idx = 0; idx < 7; idx++){ if(tables[idx](ch)){ count[idx]++; } } } for(idx = 0; idx < 7; idx++){ printf("%d ", count[idx]); } return 0; }
运行结果:
1.4 编写sort函数,对任何类型数组进行排序
#include <stdio.h> #include <stdlib.h> #include <string.h> void sort(void *array, unsigned length, unsigned int size, int(*compare)(void const *value1, void const *value2)) { //循环变量 int idx, idy; void *temp = malloc(size); for (idx = 0; idx < length - 1; idx++) { for (idy = idx + 1; idy < length; idy++) { //通过字节复制,交换位置,由于array是void类型的,所以需要根据size来进行偏移,找到对应的元素地址 if (compare(array + (idx * size), array + idy * size) == 1) { //array是指向数组的指针,根据元素大小,得到元素地址 memcpy(temp, array + idx * size, size); memcpy(array + idx * size, array + idy * size, size); memcpy(array + idy * size, temp, size); } } } } int int_compare(void const *value1, void const *value2) { if (*(int *)value1 == *(int *)value2) { return 0; } else if (*(int *)value1 <= *(int *)value2) { return -1; } else { return 1; } } int main() { int array[] = { 1, 4, 5, 2, 3, 8, 6, -10}; for (int idx = 0; idx < 8; idx++) { printf("%d ", array[idx]); } printf(" "); sort(array, 8, 4, int_compare); for (int idx = 0; idx < 8; idx++) { printf("%d ", array[idx]); } return 0; }
运行: