【C】FindString之华为软件训练营考试_动态创建一个两维数组

题目:输入一个字符串,含N(N<=100)个字符,字符全部为大写字母,不考虑输错的情况。设计一个程序,要求:把输入字符串的前i个(0<=i<=N-1)字符加入字符串的末尾组成新的字符串,这样就形成N个字符串了;对这N个字符串进行排序(字典序),不用删除重复项;能用序号查找字符串;

输入:N个字符的字符串及查找的序号

输出:对应的字符串

*********************

例子:

输入字符串:

BANANA

形成N个字符串:
BANANA
ANANAB
NANABA
ANABAN
NABANA
ABANAN

排序后的结果(序号1~6):
ABANAN
ANABAN
ANANAB
BANANA
NABANA
NANABA


代码(两维数组_动态创建与释放):

注:该代码虽然可以运行,但PC-LINT检查有N多bug,属于玩具程序。留待以后修改。

  1 #include <stdio.h>
2 #include <string.h>
3 #include <stdlib.h>
4
5 const int MAXINPUTSIZE=101;//输入的最大字符数
6 char **phead;//指向排序后的字典的首地址
7 char * _str;//存放输入的字符串
8 int StrNum;//输入字符串的字母个数
9
10 void Init()
11 {
12 phead=NULL;
13 _str=(char*)malloc(MAXINPUTSIZE*sizeof(char));
14 StrNum=0;
15 }
16 int InputString()
17 {
18 printf("请输入字符串:");
19 _str=gets(_str);
20 StrNum=strlen(_str);
21 return 1;
22 }
23 void SwapTwoPart(char * OriStr,char * RestStr,int k)//把OriStr中前面k个字符挪到最后一个字符之后,形成一个新的字符串,即为RestStr
24 {
25 int i=0,j=k;
26 while ('\0'!=OriStr[j])
27 {
28 RestStr[i]=OriStr[j];
29 i++;
30 j++;
31 }
32 j=0;
33 while (j<k)
34 {
35 RestStr[i]=OriStr[j];
36 i++;
37 j++;
38 }
39 RestStr[i]='\0';
40 }
41 void CreateDict()//创建字典,还未排序
42 {
43 int i=0;
44 phead=(char**)malloc(StrNum*sizeof(char*));
45 while (i<StrNum)
46 {
47 phead[i]=(char*)malloc(StrNum*sizeof(char*));
48 SwapTwoPart(_str,phead[i],i);
49 i++;
50 }
51
52 }
53 void BubbleSort()//冒泡排序,大的下沉
54 {
55 int i=0;
56 int j=0;
57 char *ppre=NULL;
58 char *pfol=NULL;
59 char *ptmp=(char*)malloc(StrNum*sizeof(char*));
60
61 for (i=StrNum-1;i>0;i--)
62 {
63 for (j=0;j<i;j++)
64 {
65 if(1==strcmp(phead[j],phead[j+1]))
66 {
67 strcpy(ptmp,phead[j+1]);
68 strcpy(phead[j+1],phead[j]);
69 strcpy(phead[j],ptmp);
70 }
71 }
72 }
73
74 free(ptmp);
75 }
76 void FindString()
77 {
78 int num=0;
79 char tmp[MAXINPUTSIZE];
80 while (1)
81 {
82 printf("请输入你要查找的字符串的序号(范围1~%d):",StrNum);
83 //scanf("%d",&num);//使用这个,在不小心输入字母时进入死循环!
84 gets(tmp);
85 num=atoi(tmp);
86 if ((num>0)&&(num<=StrNum))
87 {
88 printf("查询结果是 %s\n",phead[num-1]);
89 continue;
90 }
91 printf("序号超出范围!\n");
92 }
93
94 }
95 void PrintStr()
96 {
97 int i=0;
98 while (i<StrNum)
99 {
100 printf("%s\n",phead[i]);
101 i++;
102 }
103
104 }
105 void clean()
106 {
107 int i=0;
108 for (;i<StrNum;i++)
109 {
110 free(phead[i]);
111 }
112 free(phead);
113 free(_str);
114 }
115 void main()
116 {
117 Init();
118 InputString();
119 CreateDict();
120 PrintStr();
121 BubbleSort();
122 printf("\n");
123 PrintStr();
124 //FindString();
125 clean();
126 }



原文地址:https://www.cnblogs.com/caixu/p/2388285.html