|
10鱼币
字符统计个数:
对于
要求 B:统计不同的字符个数,并打印出来;
要求 C:找出出现次数最多的字符。
我的思路:分别用两个数组把不同的字符和其对应的出现次数保存起来(对应的下标一样),
可是中间的循环好像出了问题,希望大佬帮助。
- #include <stdio.h>
- #include <string.h>
- int main(void)
- {
- char str1[256];
- char str2[256] = {'0'};
- int count[256] = {0};
- int count1 = 0,i = 0,j = 0,k = 0,count2 = 0,max = 0;
-
- printf("请输入英文文本:");
- while ((str1[i++] = getchar()) != '\n')
- {
- count1++;
- }
- //printf("%s\n",str1);
- --i;
- str2[0] = str1[0];
- for (k = 1;k < i;k++)
- {
- for (j = 0; j < k; j++)
- {
- if (str1[j] == str1[k])
- {
- count[j] += 1;
- break;
- }
- if (j == k - 1)
- {
- str2[k] = str1[k];
- count[k] = 1;
- count2++;
- }
- }
- }
-
- printf("你总共输入了%d个字符,其中的不同的字符有%d个\n",count1,count2);
- printf("%s\n",str2);
- printf("它们是:");
-
- for (k = 0;k < i;k++)
- {
- if (str2[k] != '0')
- putchar(str2[k]);
- }
- putchar('\n');
-
- for (k = 1;k < i;k++)
- {
- if (count[k] >= count[k - 1])
- max = count[k];
- j = k;
- }
-
- printf("出现次数最多的字符是:'%c',它总共出现了%d次。",str2[j],max);
-
- return 0;
- }
复制代码
应该是中间这部分错了,但是我没想明白
- str2[0] = str1[0];
- for (k = 1;k < i;k++)
- {
- for (j = 0; j < k; j++)
- {
- if (str1[j] == str1[k])
- {
- count[j] += 1;
- break;
- }
- if (j == k - 1)
- {
- str2[k] = str1[k];
- count[k] = 1;
- count2++;
- }
- }
- }
复制代码
- #include <stdio.h>
- #define ASCII 128
- int main(void) {
- int total[ASCII] = {0};//一个长度位123位,可以放下ASCII码0-122位的数组,每一位代表字符出现频率
- int sum = 0;//总共出现多少个字符
- int difference = 0;//不同的字符的数量
- printf("请输入英文文本:");
- char ch;
- while((ch = getchar()) != '\n') {//只要没有输入结束,每个字符都拿到
- total[ch]++;//字符所在的ASCII码对应数组位置,上面的数量+1
- sum++;
- }
- for(int i = 0; i < ASCII; i++) {
- //printf("%d",total[i]);
- if (total[i] != 0) { //只要出现过的字符,数字必定不等于零,所以difference+1
- difference++;
- }
- }
- printf("你总共输入了%d个字符,其中不同的字符个数有%d个。\n它们是:",sum,difference);
-
- int max = 0;//出现最多的字符的次数
- int max_i = 0;//出现最多的字符所在数组的位置
- for(int i = 0; i < ASCII; i++) {
- if (total[i] != 0) {
- printf("%c",i);//每一个不同的字符都打印出来
- if (total[i] > max) { //出现频率更多的,就把频率记录下来
- max = total[i];
- max_i = i; //最高频率的位置记录下来
- }
- }
- }
- putchar('\n');
- printf("出现次数最多的字符是\'%c\',它总共出现了%d次。\n",max_i,max);
- return 0;
- }
复制代码
这是我的答案
|
|