五、编程题

1、统计一个字符串中字母、数字和空格的个数

要求:在函数中输入和输出;用一个函数指针;用函数指针调用被调函数

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #define M 100
 4 void count(int *,int *,int *,char *);
 5 
 6 
 7 int main()
 8 {
 9     char s[M];
10     void (*p)(int *,int *,int *,int *);
11     p=&count;
12     int alpha,num,blank;
13     alpha=num=blank=0;
14     printf("Input string:");
15     gets(s);
16     (*p)(&alpha,&num,&blank,s);
17     printf("alpha=%d num=%d blank=%d\n",alpha,num,blank);
18     return 0;
19 }
20 
21 void count(int *alpha,int *num,int *blank,char *s){
22     while(*s!='\0'){
23         if((*s>='a'&&*s<='z')||(*s>='A'&&*s<='Z'))
24             (*alpha)++;
25         if(*s>='0'&&*s<='9')
26             (*num)++;
27         if(*s==' ')
28             (*blank)++;
29         s++;
30     }
31 }

运行结果:

 2、对一组字符串按从小到大的顺序进行排序。

要求:在主函数输入和输出;用一个函数排序;用指向指针的方法进行排序。

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include<string.h>
 4 #define M 5
 5 #define N 20
 6 void sort(char *s[]);
 7 
 8 int main()
 9 {
10     char *s[M];
11     char *q;
12 
13     int i;
14     printf("输入%d个字符串:(回车表示结束一个字符串输入)...\n",M);
15     for(i=0;i<M;i++){
16         s[i]=(char *)malloc(sizeof(char)*N);
17         gets(s[i]);
18     }
19     sort(s);
20     printf("\n排序结果为:\n");
21     for(i=0;i<M;i++){
22         puts(s[i]);
23     }
24     return 0;
25 }
26 
27 void sort(char *s[]){
28 
29     char **ss=s;
30     char t,*temp;
31     int i,j;
32 
33 
34     for(i=0;i<M-1;i++){
35         t=i;
36         for(j=i+1;j<M;j++){
37             if(strcmp(*(s+t),*(ss+j))>0)
38                 t=j;
39         }
40 
41         if(*(ss+t)!=*(ss+i)){
42             temp=*(ss+i);
43             *(ss+i)=*(ss+t);
44             *(ss+t)=temp;
45         }
46 
47     }
48 
49 
50 }

运行结果:

 

 

 

3、奇数魔方阵

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #define M 10
 4 static int a[M][M];
 5 
 6 void f(int n){
 7     int count=1;
 8     int i=0,j=(n+1)/2;
 9     while(count<=n*n){
10         if((count%n)==1){
11             //向下填入
12             i++;
13         }else{
14             //右上填入
15             i--;
16             j++;
17         }
18 
19         //当数在第0行时
20         if(i==0)
21             i=n;
22         //当数在最后一行时
23         if(j>n)
24             j=1;
25         a[i][j]=count;
26         count++;
27     }
28 
29     for(i=1;i<=n;i++){
30         for(j=1;j<=n;j++){
31             printf("%2d ",a[i][j]);
32         }
33         printf("\n");
34     }
35 }
36 
37 int main()
38 {
39     int n;
40     scanf("%d",&n);
41     f(n);
42     return 0;
43 }

运行结果:

 

摘自:https://blog.csdn.net/weixin_43188432/article/details/104183010